<?php
namespace App\Controller;
use App\Services\APEeenheidService;
use App\Website\LinkGenerator\NewsLinkGenerator;
use App\Website\LinkGenerator\ProductLinkGenerator;
use App\Website\Navigation\BreadcrumbHelperService;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\ProductGroup;
use Pimcore\Model\DataObject\ProductSubgroup;
use Pimcore\Model\DataObject\ProductArticle;
use Pimcore\Model\Site;
use Pimcore\Model\WebsiteSetting;
use Pimcore\Twig\Extension\Templating\HeadTitle;
use Pimcore\Twig\Extension\Templating\Placeholder;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Component\Pager\PaginatorInterface;
class ProductController extends BaseController
{
/**
* @var ProductLinkGenerator
*/
protected $productLinkGenerator;
protected $productDocument;
/**
* ProductExtension constructor.
*
* @param ProductLinkGenerator $productLinkGenerator
*/
public function __construct(ProductLinkGenerator $productLinkGenerator)
{
$this->productLinkGenerator = $productLinkGenerator;
$this->productDocument = WebsiteSetting::getByName('product_document')->getData();
}
/**
* @param Request $request
* @return Response
* @Route ("{_locale}/aanbod", name="aanbod-overview")
* @throws \Exception
*/
public function overviewAction(Request $request, PaginatorInterface $paginator)
{
$subSiteKey = '*';
$page = $request->get('page', 1);
if (Site::isSiteRequest()) {
$subSiteKey = Site::getCurrentSite()->getRootDocument()->getKey();
}
$groupList = new DataObject\ProductGroup\Listing();
$groupList->setOrderKey(['orderList', 'oms']);
$groupList->setOrder('asc');
$groupList->setCondition("visible = :visible", ["visible" => "1"]); // Only visible on website
// only show required groups
$groupListGroups = [];
/** @var \Pimcore\Model\DataObject\ProductGroup $group */
foreach($groupList as $group){
$dependencies = $group->getDependencies();
$requiredBy = $dependencies->getRequiredBy();
if(!$requiredBy){
$groupListGroups[] = $group;
}
}
$paginator = $paginator->paginate(
$groupListGroups,
$page,
24
);
return $this->render('product/overview.html.twig', [
'productcategories' => $paginator,
'paginationVariables' => $paginator->getPaginationData(),
'page' => $page
]);
}
/**
* @param Request $request
* @return Response
* @Route ("{_locale}/no-product-found", name="no_product_found")
* @throws \Exception
*/
public function noProductFoundAction(Request $request, PaginatorInterface $paginator)
{
$subSiteKey = '*';
$page = $request->get('page', 1);
if (Site::isSiteRequest()) {
$subSiteKey = Site::getCurrentSite()->getRootDocument()->getKey();
}
$groupList = new DataObject\ProductGroup\Listing();
$groupList->setOrderKey(['orderList', 'oms']);
$groupList->setOrder('asc');
$groupList->setCondition("visible = :visible", ["visible" => "1"]); // Only visible on website
// only show required groups
$groupListGroups = [];
/** @var \Pimcore\Model\DataObject\ProductGroup $group */
foreach($groupList as $group){
$dependencies = $group->getDependencies();
$requiredBy = $dependencies->getRequiredBy();
if(!$requiredBy){
$groupListGroups[] = $group;
}
}
$paginator = $paginator->paginate(
$groupListGroups,
$page,
24
);
return $this->render('product/overview.html.twig', [
'productcategories' => $paginator,
'paginationVariables' => $paginator->getPaginationData(),
'page' => $page
]);
}
/**
* @param Request $request
* @Route("{_locale}/{path}/{key}~g{id}", name="group-overview", defaults={"path"=""}, requirements={"path"=".*?", "key"="[\w-]+", "id"="\d+"})
*
* @return Response
*
* @throws \Exception
*/
public function groupoverviewAction(Request $request, PaginatorInterface $paginator)
{
$category = ProductGroup::getById($request->get('id'));
// Check if visible
if(!$category->getVisible()){
throw new NotFoundHttpException('Not public.');
}
$page = $request->get('page', 1);
$subSiteKey = '*';
if (Site::isSiteRequest()) {
$subSiteKey = Site::getCurrentSite()->getRootDocument()->getKey();
}
// Check if categories are combined
$dependencies = $category->getDependencies();
$requires = $dependencies->getRequires();
$requiredBy = $dependencies->getRequiredBy();
if($requiredBy){
// Goto first DataObject
foreach ($requiredBy as $requireby){
if($requireby['type'] == 'object'){
$objectId = $requireby['id'];
$objectData = \Pimcore\Model\DataObject::getById($objectId);
if($objectData->getClassName() == 'productGroup'){
// redirect to RequiredBy Object
$redirectUrl = $this->productLinkGenerator->generate($objectData, ['document' => $this->productDocument]);
return $this->redirect($redirectUrl);
}
}
}
}
$foundIds = [];
foreach ($requires as $require){
if($require['type'] == 'object'){
$objectId = $require['id'];
// $objectData = \Pimcore\Model\DataObject::getById($objectId);
$foundIds[] = $objectId;
}
}
$subcategoryList = new DataObject\ProductSubgroup\Listing();
$subcategoryList->setCondition("o_parentId = :groupid", ["groupid" => $request->get('id')]);
if($foundIds){
foreach ($foundIds as $foundId){
$subcategoryList->addConditionParam("o_parentId = $foundId", "", "OR");
}
}
$subcategoryList->setOrderKey(['orderList', 'oms']);
// $subcategoryList->setOrderKey('oms');
$subcategoryList->setOrder('asc');
$subcategoryList->setLimit(1);
// Goto first in line
$firstSubCategory = $subcategoryList->load();
if(count($firstSubCategory) > 0){
$foundSubCategory = $firstSubCategory[0];
$foundCategory = $foundSubCategory->getParent();
$redirectUrl = $this->productLinkGenerator->generateSubgroup($foundCategory, $foundSubCategory, ['document' => $this->productDocument]);
return $this->redirect($redirectUrl);
}else{
throw new NotFoundHttpException('Product subcategory not found.');
}
// $paginator = $paginator->paginate(
// $subcategoryList,
// $page,
// 16
// );
//
// return $this->render('product/groupoverview.html.twig', [
// 'category' => $category,
// 'productsubcategories' => $paginator,
// 'paginationVariables' => $paginator->getPaginationData(),
// 'page' => $page
// ]);
}
/**
* @Route("{_locale}/{path}/{gkey}~g{gid}/{key}~sg{id}", name="subgroup-overview", defaults={"path"=""}, requirements={"path"=".*?", "key"="[\w-]+", "id"="\d+"})
*
* @param Request $request
*
* @return Response
*/
public function suboverviewAction(Request $request, PaginatorInterface $paginator)
{
$subSiteKey = '*';
if (Site::isSiteRequest()) {
$subSiteKey = Site::getCurrentSite()->getRootDocument()->getKey();
}
$category = ProductGroup::getById($request->get('gid'));
// Check if visible
if(!$category->getVisible()){
throw new NotFoundHttpException('Not public.');
}
$subcategory = ProductSubgroup::getById($request->get('id'));
$page = $request->get('page', 1);
// Check if categories are combined
$dependencies = $category->getDependencies();
$requires = $dependencies->getRequires();
$requiredBy = $dependencies->getRequiredBy();
$foundIds = [];
if($requiredBy){
// Goto first DataObject
foreach ($requiredBy as $requireby){
if($requireby['type'] == 'object'){
$objectId = $requireby['id'];
$foundIds[] = $objectId;
}
}
}
foreach ($requires as $require){
if($require['type'] == 'object'){
$objectId = $require['id'];
$foundIds[] = $objectId;
}
}
$subcategoryList = new DataObject\ProductSubgroup\Listing();
$subcategoryList->setCondition("o_parentId = :groupid", ["groupid" => $request->get('gid')]);
if($foundIds){
foreach ($foundIds as $foundId){
$subcategoryList->addConditionParam("o_parentId = $foundId", "", "OR");
}
}
$subcategoryList->setOrderKey(['orderList', 'oms']);
$subcategoryList->setOrder('asc');
$subcategoryList = $subcategoryList->load();
if (!($subcategory instanceof ProductSubgroup && ($subcategory->isPublished() || $this->verifyPreviewRequest($request, $subcategory)))) {
throw new NotFoundHttpException('Product subcategory not found.');
}
$subSiteKey = '*';
if (Site::isSiteRequest()) {
$subSiteKey = Site::getCurrentSite()->getRootDocument()->getKey();
}
// Fetch Merken
$merkArr = [];
if(is_numeric( $request->get('id') )){
$classIdProductArticle = DataObject\ProductArticle::classId();
$dbArtciles = \Pimcore\Db::get();
$sqlSelect = "SELECT `merk` FROM `object_".$classIdProductArticle."` WHERE `merk` IS NOT NULL AND o_parentId = ".$request->get('id');
// $sqlSelect = "SELECT `merk` FROM `object_".$classIdProductArticle."` WHERE `merk` IS NOT NULL";
$dataFound = $dbArtciles->fetchAll($sqlSelect);
$merkenFound = array_unique(array_column($dataFound, 'merk'));
foreach($merkenFound as $merk){
if ($merk === ""){
$merk = "Overige merken";
$merkArr[] = $merk;
}else{
$merkArr[] = $merk;
}
}
sort($merkArr);
}
// Filter on
// ($request->get('merken')||$request->get('stock')||$request->get('price'))
if ($request->isXmlHttpRequest() && $request->get('filteredResults', true)){
$productList = new DataObject\ProductArticle\Listing();
$productList->setCondition("o_parentId = :parentId", ["parentId" => $request->get('id')]);
$productList->setOrderKey(['merk','oms']);
$productList->setOrder("asc");
$merken = $request->get('merken', []);
$stocks = $request->get('stock', []);
$price = $request->get('price');
$addExtraCondition = '';
if ($stocks && count($stocks) > 0) {
$excludedStocks = array_diff([0, 1, 2], $stocks);
$stocksItems = [
'`stock` <= 0',
'(`stock` <= `aantalVerkochtLaatsteMaand` AND (`stock` > 0))',
'(`stock` >= `aantalVerkochtLaatsteMaand` AND (`stock` > 0))',
];
foreach ($excludedStocks as $excludedStock) {
unset($stocksItems[$excludedStock]);
}
if (count($stocksItems) > 0) {
$addExtraCondition .= "AND (" . implode(" OR ", $stocksItems) . ") ";
}
}
if ($price) {
if ($price[0] === 'up'){
$productList->setOrderKey("prijs");
$productList->setOrder("desc");
}
if ($price[0] === 'down'){
$productList->setOrderKey("prijs");
$productList->setOrder("asc");
}
}
if ($merken && count($merken) > 0) {
$addExtraCondition .= "AND ( `merk` = '". implode("' OR `merk` = '", $merken). "')";
}
$productList->setCondition("o_parentId = :parentId $addExtraCondition", ["parentId" => $request->get('id')]);
$paginator = $paginator->paginate(
$productList,
$page,
36
);
$result = $this->renderView('includes/product/suboverview.html.twig',
[
'category' => $category,
'subcategory' => $subcategory,
'productlist' => $paginator,
'subcategoryList' => $subcategoryList,
'merken' => $merkArr
]
);
$pagination = $this->renderView('includes/pagination-product-ajax.html.twig',
[
'paginationVariables' => $paginator->getPaginationData(),
'pageselected' => $request->get('page')
]
);
if($productList->count()){
$respond['products'] = $result;
$respond['pagination'] = $pagination;
}else{
$respond['products'] = '<div class="col-md-12">Geen artikels teruggevonden.</div>';
$respond['pagination'] = '';
}
return new JsonResponse($respond);
} else {
$productList = new DataObject\ProductArticle\Listing();
$productList->setCondition("o_parentId = :parentId", ["parentId" => $request->get('id')]);
$productList->setOrderKey(['merk','oms']);
$productList->setOrder("asc");
$productList->setCondition("o_parentId = :parentId AND `merk` != '' AND `merk` IS NOT NULL AND `stock` != '' AND `stock` IS NOT NULL", ["parentId" => $request->get('id')]);
$paginator = $paginator->paginate(
$productList,
$page,
36
);
}
return $this->render('product/suboverview.html.twig', [
'category' => $category,
'subcategory' => $subcategory,
'productlist' => $paginator,
'subcategoryList' => $subcategoryList,
'paginationVariables' => $paginator->getPaginationData(),
'pageselected' => $page,
'merken' => $merkArr
]);
}
/**
* @Route("{_locale}/{path}/{gkey}~g{gid}/{sgkey}~sg{sgid}/{key}~pi{id}", name="article-detail", defaults={"path"=""}, requirements={"path"=".*?", "key"="[\w-]+", "id"="\d+"})
*
* @param Request $request
*
* @return Response
*/
public function detailAction(Request $request)
{
$category = ProductGroup::getById($request->get('gid'));
// Check if visible
if(!$category->getVisible()){
throw new NotFoundHttpException('Not public.');
}
$subcategory = ProductSubgroup::getById($request->get('sgid'));
$productArticle = ProductArticle::getById($request->get('id'));
if (!($category instanceof ProductGroup && ($category->isPublished() || $this->verifyPreviewRequest($request, $category)))) {
throw new NotFoundHttpException('ProductCategory not found.');
}
if (!($subcategory instanceof ProductSubgroup && ($subcategory->isPublished() || $this->verifyPreviewRequest($request, $subcategory)))) {
throw new NotFoundHttpException('ProductSubcategory not found.');
}
if (!($productArticle instanceof ProductArticle && ($productArticle->isPublished() || $this->verifyPreviewRequest($request, $productArticle)))) {
throw new NotFoundHttpException('ProductArticle not found.');
}
$APEeenheidService = new APEeenheidService();
return $this->render('product/detail.html.twig', [
'category' => $category,
'subcategory' => $subcategory,
'product' => $productArticle,
'orderByQuantity' => $APEeenheidService->getOrderByFromAPE($productArticle->getAPEeenheid())
]);
}
/**
* @Route("{_locale}/product/{code}", name="article-short-code-detail")
*
* @param Request $request
*
* @return Response
*/
public function detailShortCodeAction(Request $request)
{
if (ProductArticle::getByCode($request->get('code'))->getData() !== []){
$productArticle = ProductArticle::getByCode($request->get('code'))->getData()[0];
$subcategory = $productArticle->getParent();
$category = $subcategory->getParent();
$shortLink = true;
if (!($category instanceof ProductGroup && ($category->isPublished() || $this->verifyPreviewRequest($request, $category)))) {
throw new NotFoundHttpException('ProductCategory not found.');
}
if (!($subcategory instanceof ProductSubgroup && ($subcategory->isPublished() || $this->verifyPreviewRequest($request, $subcategory)))) {
throw new NotFoundHttpException('ProductSubcategory not found.');
}
if (!($productArticle instanceof ProductArticle && ($productArticle->isPublished() || $this->verifyPreviewRequest($request, $productArticle)))) {
throw new NotFoundHttpException('ProductArticle not found.');
}
$APEeenheidService = new APEeenheidService();
return $this->render('product/detail.html.twig', [
'category' => $category,
'shortLink' => $shortLink,
'subcategory' => $subcategory,
'product' => $productArticle,
'orderByQuantity' => $APEeenheidService->getOrderByFromAPE($productArticle->getAPEeenheid())
]);
}
return $this->redirect('/nl');
}
}