<?php
namespace App\Controller;
use App\Entity\User;
use App\Service\UserService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use App\Entity\UIPage;
// use App\Entity\Category;
use App\Entity\CartCoupon;
use App\Entity\Company;
use App\Entity\Image;
use App\Entity\Testimony;
use App\Entity\Product;
use App\Entity\Pricing;
use App\Entity\ProductSponsored;
use App\Entity\ProductSponsoredCategory;
use App\Entity\NewsLetterSubscriber;
use App\Entity\CmsHomePage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Form\NewsLetterSubscribeType;
class FrontEndController extends AbstractController
{
/**
* @var UserService
*/
private $userServ;
public function __construct(SessionInterface $session, UserService $userServ)
{
$this->userServ = $userServ;
$this->session = $session;
}
/**
* @Route("/connexion", name="ConnexionFrancais")
* Redirect the user to the right entry point depending of it's current locale
*/
public function connexion(){
return $this->redirectToRoute('fos_user_security_login');
}
/**
* @Route("/inscription", name="InscriptionFrancais")
* Redirect the user to the right entry point depending of it's current locale
*/
public function inscription(){
return $this->redirectToRoute('fos_user_registration_register');
}
/**
* @Route(
* "/",
* name="home",
* )
* @Template("frontend/homepage.html.twig")
*/
public function home(UserService $userServ, EntityManagerInterface $em, Request $request){
if ($this->userServ->getAssociationUserIsBrowsing()){
return $this->redirectToRoute('companyAssociationList', [
'urlName' => $this->userServ->getAssociationUserIsBrowsing()->getUrlName()
]);
}
$twigData = array();
$form = null;
$CMSHomePage = $em->getRepository(CmsHomePage::class)->findOneBy(["dataKey"=>"CMSHomePage"]);
if ($CMSHomePage) {
if (!empty($CMSHomePage->getDataValue())) {
$form = json_decode($CMSHomePage->getDataValue(), true);
}
}
// if (!$form) {
// $file = 'data/CMSHomePage.json';
// if(file_exists($file)){
// //File exists let's load
// $rawData = file_get_contents($file);
// $form= json_decode($rawData, true);
//
// }else{
// die('CMS: File missing');
// }
// }
$form['producerOfTheWeek'] = $em->getRepository(Company::class)->findOneBy(
[
'id' => $form['producerOfTheWeek']
]
);
$twigData['CMS'] = $form;
$twigData['testimony'] = $em->getRepository(Testimony::class)->getOneRandom();
$SponsoredItems = [];
$sponsored_products_per_category_limit = 4;
$ProductSponsoredCategories = $em->getRepository(ProductSponsoredCategory::class)->findAllFrontPage();
foreach($ProductSponsoredCategories as $psc) {
$category = $psc->getCategory();
$Products = [];
$_SponsoredProducts = $em->getRepository(ProductSponsored::class)->findInSponsoredLimit($psc, $sponsored_products_per_category_limit);
foreach($_SponsoredProducts as $SponsoredProduct) {
$_product = $SponsoredProduct->getProduct();
$Products[] = $_product;
}
if ($category && count($Products) < $sponsored_products_per_category_limit) {
$ExtraSponsoredProducts = $em->getRepository(Product::class)->getProductsFromCategoryForFrontpage(
$category, $sponsored_products_per_category_limit
);
foreach($ExtraSponsoredProducts as $ExtraSponsoredProduct) {
$Products[] = $ExtraSponsoredProduct;
}
}
// Remove duplicate products
$_Products = [];
foreach($Products as $Product) {
$_Products[$Product->getId()] = $Product;
}
$Products = $_Products;
shuffle($Products);
$SponsoredItems[] = array(
"SponsoredCategory" => $psc,
"Products" => $Products
);
}
$twigData['SponsoredItems'] = $SponsoredItems;
$productsOnSale = $em->getRepository(Pricing::class)->findOnSaleFrontpage();
$allProductsOnSale = array();
foreach($productsOnSale as $p){
if($p->getDiscountProduct() && $p->getDiscountProduct()->isSalable()
&& !$p->getDiscountProduct()->getIsDisplayedInAssociationOnly()
) {
if($p->getDiscountProduct()->getDeliveryType() == 0){
$allProductsOnSale[] = $p->getDiscountProduct();
}
}
}
$twigData['allProductsOnSale'] = $allProductsOnSale;
/**********************************
* Let's add the subscribers form
**********************************/
if ($request->isMethod('post')) {
$posts = $request->request->all();
if (isset($posts["action"])) {
if ($posts["action"] == "newsletter_subscribe") {
if (!empty($posts["newsletter_email"])) {
$email = $posts["newsletter_email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->addFlash('error', 'Il y a un problème avec votre courriel!');
} else {
$subscriber = new NewsLetterSubscriber();
$subscriber->setEmail($email);
try {
$em = $this->getDoctrine()->getManager();
$em->persist($subscriber);
$em->flush();
/*
create 10% coupon
*/
$coupon_code = substr('C-'.md5(uniqid()), 0, 12);
$coupon = new CartCoupon();
$coupon->setOneTimeOnly(true);
$coupon->setType(0);
$coupon->setAmount(10);
$coupon->setCode($coupon_code);
$coupon->setDateFrom(new \DateTime());
$coupon->setDateTo(new \DateTime("+1 year"));
$em->persist($coupon);
$em->flush();
$email_body = $this->get('twig')->render('emails/welcomeNewsLetter.html.twig', array('coupon_code' => $coupon_code));
$userServ->sendEmail('Votre coupon rabais de 10% chez Maturin!', $email_body, false, $email);
$this->session->set('DO_NOT_DISPLAY_STARTERKITS', "TRUE");
$this->addFlash('success', 'Vous êtes maintenant inscrit a notre infolettre!');
}
catch (\Exception $e ){
if(stristr($e->getMessage(), 'duplicate')){
$this->addFlash('error', 'Vous êtes déja inscrit!');
} else {
$this->addFlash('error', 'Une erreur c\'est produite: '.$e->getMessage());
}
return $this->redirectToRoute('home');
}
}
return $this->redirectToRoute('home');
}
}
}
}
$subscriber = new NewsLetterSubscriber();
$form = $this->createForm(NewsLetterSubscribeType::class, $subscriber);
$twigData['formSubscriber'] = $form->createView();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$subscriber = $form->getData();
if (!filter_var($subscriber->getEmail(), FILTER_VALIDATE_EMAIL)) {
$this->addFlash('error', 'Il y a un problème avec votre courriel!');
$this->addFlash('focus', 'form[name=news_letter_subscribe]');
return $twigData;
}
try {
$em = $this->getDoctrine()->getManager();
$em->persist($subscriber);
$em->flush();
$this->addFlash('success', 'Vous êtes maintenant inscrit a notre infolettre!');
$this->addFlash('focus', 'form[name=news_letter_subscribe]');
}
catch (\Exception $e ){
if(stristr($e->getMessage(), 'duplicate')){
$this->addFlash('error', 'Vous êtes déja inscrit!');
$this->addFlash('focus', 'form[name=news_letter_subscribe]');
}
return $this->redirectToRoute('home');
}
}
$user= $userServ->getuser();
$twigData['userPaidOrders']=false;
if($user){
$twigData['userPaidOrders'] = $user->getAllCartsProducts();
}
return $twigData;
}
}