<?php
namespace App\Controller;
use ContainerELzgxgm\getGoogleMapService;
use DateTime;
use Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Pimcore\Config;
use Pimcore\Model\DataObject;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\DataObject\ProductMarca;
use Pimcore\Model\Document;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\Service\Product\ProductHelper;
#use App\Ecommerce\Tool\RecentlyViewedProducts;
use App\Model\DefaultProduct;
use App\Model\ShopCategory;
use App\Model\DefaultMarca;
use App\Service\HelperService;
//use OutputDataConfigToolkitBundle\Service;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\Helper;
use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface;
use Pimcore\Model\DataObject\Product;
use Pimcore\Model\DataObject\ProductCategory;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
#use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\User\UserInterface;
use Knp\Component\Pager\Pagination\SlidingPagination;
use Knp\Component\Pager\PaginatorInterface;
class ContentController extends FrontendController {
public function defaultAction(
Request $request,
HelperService $helperService,
Config $config
) {
return $this->render('Shop/ProductDetails/productDetail.html.twig');
//return new Response("views must be change to twig");
// $this->checkAccess($request);
// $this->setCookieTemplate();
//recuperar la key del systemSettings.
$apikey = $config['services']['google']['browser_api_key'];
//listar las dos tiendas con el condicional.
$companies = new DataObject\Company\Listing();
$companies->setCondition("sede = ?", 1);
$companies->setOrderKey("title");
//test
$puntodeventa = new DataObject\Colaborador\Listing();
$puntodeventa->setOrderKey(["comunidad_autonoma","provincia","ciudad","name"]);
$puntodeventa->setCondition("ispuntoventa = ?", 1);
$puntodeventa->addConditionParam("showinweb = ?", 1, "AND");
$this->view->puntodeventa = $puntodeventa;
$aplicadores = new DataObject\Colaborador\Listing();
$aplicadores->setOrderKey(["comunidad_autonoma","provincia","ciudad","name"]);
$aplicadores->setCondition("isaplicador = ?", 1);
$aplicadores->addConditionParam("showinweb = ?", 1, "AND");
$this->view->aplicadores = $aplicadores;
$this->view->companies = $companies;
$this->view->apikey = $apikey;
$this->view->unique = $helperService->generateUniqueCode();
}
public function homeAction(UserInterface $user = null, Request $request){
$lang = $request->getLocale();
$params = [];
$ratesDateCookie = $request->cookies->get('lastRatesChanges');
// $eventsDateCookie = json_decode($request->cookies->get('lastEventsChanges'), true) ?? [];
$filePath = __DIR__.'/../../public/var/assets/excel_de_tarifas/temp/changes.xlsx';
try {
$spreadsheet = IOFactory::load($filePath);
$sheet = $spreadsheet->getActiveSheet();
$lastRow = $sheet->getHighestRow();
$lastChanges = $sheet->getCell('A'.$lastRow);
} catch (Exception){
$lastChanges = null;
}
// $documentName = $lang == 'en' ? '/recent-events' : '/eventos-recientes';
// $document = Document::getByPath('/'.$lang.$documentName);
// $modificationDate = $document->getModificationDate();
if ($user){
if (isset($ratesDateCookie) && $ratesDateCookie < $lastChanges) {
$params['modal'] = $lastChanges;
}
// if (!is_array($eventsDateCookie)) {
// $eventsDateCookie = [];
// }
//
// if (!isset($eventsDateCookie[$lang])) {
// $eventsDateCookie[$lang] = null;
// }
//
// if($eventsDateCookie[$lang] < $modificationDate ){
$params['events'] = true; // <- if modal has to appear only when changes are made, change this variable to $modificationDate
// $eventsDateCookie[$lang] = $modificationDate;
// }
//
// $eventCookieData = json_encode($eventsDateCookie);
$response = new Response();
$response->headers->setCookie(new Cookie('lastRatesChanges', $lastChanges, strtotime('now + 30 days')));
// $response->headers->setCookie(new Cookie('lastEventsChanges', $eventCookieData, strtotime('now + 30 days')));
$response->sendHeaders();
}
$params["categories"] = $this->getCategories();
$params["marcas"] = $this->getMarcas();
$params["companies"] = $this->getCompanies();
return $this->render('Default/index.html.twig', $params);
}
protected function getCategories(): DataObject\ProductCategory\Listing
{
$categories = new DataObject\ProductCategory\Listing();
$categories->setUnpublished(false);
$categories->setOrderKey("order");
$categories->setCondition('o_parentId = ?', [10]);
$categories->load();
return $categories;
}
protected function getMarcas(): DataObject\ProductMarca\Listing
{
$marcas = new DataObject\ProductMarca\Listing();
$marcas->setUnpublished(false);
$marcas->setOrderKey("order");
$marcas->load();
return $marcas;
}
protected function getCompanies(): DataObject\Company\Listing
{
$companies = new DataObject\Company\Listing();
$companies->setOrderKey(["sede","title"]);
$companies->setOrder(["desc","asc"]);
$companies->load();
return $companies;
}
public function aboutUsAction(Request $request){
return $this->render('Content/aboutUs.html.twig');
}
public function footerAction(Request $request){
return $this->render('include/footer.html.twig');
}
public function pointsOfSaleAction(Request $request){
//getting objects
$colaboradores = new DataObject\Colaborador\Listing();
$colaboradores->setCondition("showinweb = ?", 1);
$colaboradores->addConditionParam("showinmap = ?", 1, "AND");
$colaboradores->setOrderKey("name");
$company = DataObject\Company::getById(415);
return $this->render('Content/pointsOfSale.html.twig',[
'collaborators' => $colaboradores,
'company' => $company
]);
}
public function indrustryProfessionalsAction(Request $request){
//getting objects
$professionals = new DataObject\Colaborador\Listing();
$professionals->addConditionParam("showinweb = ?", 1);
$professionals->addConditionParam("showinmap = ?", 1, "AND");
$professionals->setOrderKey("name");
$brands = $professionals->getClass()->getFieldDefinition("brands");
$specialitazions = $professionals->getClass()->getFieldDefinition("specialization");
$brands = $brands->getOptions();
$specialitazions = $specialitazions->getOptions();
$company = DataObject\Company::getById(415);
return $this->render('Content/industryProfessionals.html.twig',[
'professionals' => $professionals,
'company' => $company,
'brands' => $brands,
'specializations' => $specialitazions
]);
}
/**
* @Route("/ajax_professional", name="ajax_professional")
*/
public function modalProfessionalsAjaxAction(Request $request){
$id = $request->get('data');
$lang = $request->get('lang');
//getting objects
$professional = DataObject\Colaborador::getById($id);
$company = DataObject\Company::getById(415);
return $this->render('Content/dataProfessionalsModal.html.twig',
[
'professional' => $professional,
'company' => $company,
'lang' => $lang
]);
}
/**
* @Route("/detailCart", name="detailCart")
* @Security("is_granted('ROLE_USER')")
*/
public function detailCartAction(Request $request){
return $this->render('Cart/main-cart.html.twig');
}
public function tarifaAction(
Request $request,
HelperService $helperService
) {
$pdfFile = "BSN";
/*
$orgFolder = PIMCORE_PRIVATE_VAR . "/securePDF/" ;
if (file_exists($orgFolder . $pdfFile )) {
$copyFolder = PIMCORE_WEB_ROOT . "/static2/pdfjsviewer/tmpPdf/";
$tmpFileName = uniqid() . ".pdf";
copy($orgFolder . $pdfFile , $copyFolder . $tmpFileName);
$this->view->pdf = $tmpFileName;
}*/
$params = [];
$params["unique"] = $helperService->generateUniqueCode();
$params["pdf"] = $pdfFile;
return $this->render('PDF/viewerframe.html.twig', $params);
}
#[Route('/tarifaPDF/{pdf}', name: 'tarifa-pdf-view')]
public function tarifaPDFAction(
Request $request,
$pdf,
HelperService $helperService
) {
$pdf = $pdf.'.pdf';
$parameters = array(
//Same parameters as defalt viewer.
//Tell to the bundle where is the pdf. (absolute path for outside temporal folder pdf, just the <name>.pdf for inside temporal folder)
'pdf' => $pdf ,
//Tell to the bundle that its necessary to delete pdf after render.
'deletePdfInTmpAfterRenderized' => false,
//pdf.js viewer options
'showToolBar' => true,
'showLeftToolbarButton' => true,
'showSearchInDocumentButton' => true,
'showPreviousPageButton' => true,
'showPreviousPageButton' => true,
'showFindPageInputText' => true,
'showNumberOfPagesLabel' => true,
'showZoomInButton'=> true,
'showZoomOutButton'=> true,
'showScaleSelectComboBox'=> true,
'showPresentationModeButton'=> true,
'showOpenFileButton'=> false,
'showPrintButton'=> false,
'showDownloadButton'=> false,
'showViewBookmarkButton'=> false,
'showToolsButton'=> true,
);
// $this->view->unique = $helperService->generateUniqueCode();
// return $this->render('PDF/custom.html.php', $parameters);
return $this->render('PDF/custom.html.twig',$parameters);
}
/**
* Pdf system deletion from tmpDir
*
* @param string $PdfTmpPath , relative path to the pdf from webroot dir
* @Route("/deletePDF")
*
* @return Response, Error in pdf deletion. If it's ok, this function must return an empty string.
*/
public function deletePDF (Request $request){
try{
unlink(substr($request->get('PdfTmpPath'), 1));
} catch (Exception $e){
return new Response('Can not delete pdf file from temporal directory, '.$e->getMessage().', please configure tmpPdfDirectory and pdf variables');
}
return new Response('');
}
public function cuantapinturanecesarioresultAction(
Request $request,
HelperService $helperService
) {
$this->checkAccess($request);
$this->setCookieTemplate();
$this->view->unique = $helperService->generateUniqueCode();
}
/**
* marcasAction
*
* @param Request $request
* @param HelperService $helperService
* @return void
*/
public function marcasAction(
Request $request,
HelperService $helperService
) {
$this->checkAccess($request);
$this->setCookieTemplate();
$marcas = new DataObject\ProductMarca\Listing();
$marcas->setUnpublished(false);
$marcas->setOrderKey("order");
$this->view->marcas = $marcas;
$this->view->unique = $helperService->generateUniqueCode();
\Pimcore\Cache::disable();
}
/**
* categoriasAction
*
* @param Request $request
* @param HelperService $helperService
* @return void
*/
public function categoriasAction(
Request $request,
HelperService $helperService
) {
$this->checkAccess($request);
$this->setCookieTemplate();
$categories = new DataObject\ProductCategory\Listing();
$categories->setUnpublished(false);
$categories->setOrderKey("order");
$categories->setCondition('o_path LIKE ?', ['/Categorias de producto/']);
// $categories->setCondition('(productos IS NOT NULL OR productos <> \'\') AND o_path LIKE ?', ['/Categorias de producto/']);
$this->view->categories = $categories;
$this->view->unique = $helperService->generateUniqueCode();
\Pimcore\Cache::disable();
}
/**
* @Route("/colaboradoresmap/{lang}")
*/
public function colaboradoresmapAction(
Request $request,
$lang,
HelperService $helperService,
Config $config) {
$this->checkAccess($request);
$this->setCookieTemplate();
$apikey = $config['services']['google']['browser_api_key'];
$colaboradores = new DataObject\Colaborador\Listing();
$colaboradores->setCondition("showinweb = ?", 1);
$colaboradores->addConditionParam("showinmap = ?", 1, "AND");
$colaboradores->setOrderKey("name");
$this->view->unique = $helperService->generateUniqueCode();
return $this->render(":Content:puntodeventamap.html.php", ["colaboradores" => $colaboradores, "linkTitle" => $this->get("translator")->trans("lnk_open_in_google_map", array(), null, $lang), "api_key" => $apikey]);
// $this->view->colaboradores = $colaboradores;
}
public function setCookieTemplate() {
$cookieListener = $this->get(\Pimcore\Bundle\CoreBundle\EventListener\Frontend\CookiePolicyNoticeListener::class);
$cookieListener->loadTemplateFromResource("@App/Resources/views/Misc/cookie-policy-bsn-template.html");
}
private function checkAccess(Request $request) {
if (!(($request->query->get('pimcore_preview') == "true") || ($request->query->get('pimcore_editmode') == "true"))) {
// $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
}
}
/**
* @Route("/squareMeters", name="squareMeters")
*
*/
public function squareMetersAction(Request $request){
return $this->render('Content/squareMeters.html.twig');
}
/**
* @Route("/calculatePaint", name="calculatePaint")
*
*/
public function calculatePaintAction(Request $request){
return $this->render('Content/calculatePaint.html.twig');
}
/**
* @Route("/paintingSchemes", name="paintingSchemes")
*
*/
public function paintingSchemesAction(){
return $this->render('Content/paintingSchemes.html.twig');
}
#[Route('/rates', name: 'rates-view')]
public function ratesView(Request $request): Response
{
$locale = $request->getLocale();
$params['_locale'] = $locale;
//get the Excel file with the price changes
$filePath = __DIR__.'/../../public/var/assets/excel_de_tarifas/temp/changes.xlsx';
$arrayData = [];
try {
$spreadsheet = IOFactory::load($filePath);
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$value = $sheet->getCell('A' . $row->getRowIndex())->getValue();
$brands = [];
foreach ($sheet->getColumnIterator('B') as $column){
$columnIterator = $column->getCellIterator();
$columnIterator->setIterateOnlyExistingCells(false);
$brandName = $sheet->getCell($column->getColumnIndex().$row->getRowIndex())->getValue();
$brands[] = ProductMarca::getByName($brandName)->load();
}
$date = new DateTime();
$date->modify('+' . $value . ' days');
$formattedDateFull = strftime('%e %B %Y', $value);
$arrayData[] = [
'date' => $formattedDateFull,
'brands' => $brands
];
}
} catch (Exception){
}
$params['path'] = '/excel_de_tarifas/ExporterWeb.xlsx';
$params['changes'] = $arrayData;
return $this->render('Content/rates.html.twig', $params);
}
#[Route('/recent-events', name: 'recent-events')]
public function eventsViewAction(): Response
{
return $this->render('Content/events.html.twig');
}
/**
* @Route("/calculatePaintResult", name="calculatePaintResult")
*
*/
public function calculatePaintResultAction(
Request $request,
Factory $ecommerceFactory,
HelperService $helperService,
ListHelper $listHelper,
PaginatorInterface $paginator,
){
$params = array_merge($request->query->all(), $request->attributes->all(), $request->request->all());
$resultado = array();
if (!empty($params['limit'])) {
$limit = $params['limit'];
}
$resultado["tipo-embarcacion"] = $params["radio_1"];
if (preg_match("/^mo/i", $params["radio_1"])) {
$resultado["tipo-embarcacion"] = $resultado["tipo-embarcacion"] . $params["radio_2"];
}
$resultado["base-embarcacion"] = $params["radio_3"];
$resultado["dimension-eslora"] = $params["value1"];
$resultado["dimension-calado"] = $params["value2"];
$resultado["dimension-manga"] = $params["value3"];
$resultado["resultado-litre"] = round(floatval($params["value_1"]), 2);
if (!key_exists("calculvariant", $params)) {
if (empty($params["calculvariant"])) {
$params["calculvariant"] = $params["value_hidden"];
}
}
if ($request->get('filterdefinition') instanceof \Pimcore\Model\DataObject\FilterDefinition) {
$filterDefinition = $request->get('filterdefinition');
}
if (empty($filterDefinition)) {
$filterDefinition = \Pimcore\Config::getWebsiteConfig()->get('resultcuantapinturaFilterdefinition');
}
if (empty($limit)) {
$limit = $filterDefinition->getPageLimit();
}
//setting assortment tenant
$environment = $ecommerceFactory->getEnvironment();
$environment->setCurrentAssortmentTenant("default");
// create product list
$indexService = $ecommerceFactory->getIndexService();
$products = $indexService->getProductListForCurrentTenant();
$products->setVariantMode(ProductListInterface::VARIANT_MODE_HIDE);
$products->addCondition("productstatus NOT IN ('new','decatelogized','for_delete') OR productstatus IS NULL", 'productstatus');
$products->addCondition("calculvariant LIKE '%#" . $params["value_hidden"] . "#%'", 'calculvariant');
$params["products"] = $products;
// create and init filter service
$filterService = $ecommerceFactory->getFilterService();
$listHelper->setupProductList($filterDefinition, $products, $params, $filterService, true);
$params["filterService"] = $filterService;
$params["filterDefinition"] = $filterDefinition;
$currentPage = $request->get('page', 1);
$productTotal = count($products);
$maxPage = ceil($productTotal / $limit);
if($currentPage > $maxPage){
$currentPage = $maxPage;
}
/** @var SlidingPagination $paginator */
$paginator = $paginator->paginate(
$products,
$currentPage,
$limit
);
$params["paginator"] = $paginator;
$params['paginationVariables'] = $paginator->getPaginationData();
$params['perPage'] = $limit;
$params['resultado'] = $resultado;
return $this->render('Content/calculatePaintResult.html.twig',$params);
}
public function privacyPolicyAction(){
return $this->render('Content/policy/privacyPolicy.html.twig');
}
public function termsAndConditionsAction(){
return $this->render('Content/policy/termsAndConditions.html.twig');
}
public function dataProtectionAction(){
return $this->render('Content/policy/dataProtection.html.twig');
}
public function cookiePolicyAction(){
return $this->render('Content/policy/cookiePolicy.html.twig');
}
}