<?php 
 
namespace App\Controller; 
 
use App\Entity\CompanyAssociation; 
use App\Entity\ProductAdjustment; 
use Doctrine\ORM\Mapping\ClassMetadataInfo; 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 
use Symfony\Component\Routing\Annotation\Route; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Session\SessionInterface; 
 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity; 
 
use Doctrine\ORM\EntityManagerInterface; 
use Doctrine\ORM\Query\ResultSetMapping; 
 
use App\Entity\Company; 
use App\Entity\Product; 
use App\Entity\Cart; 
use App\Entity\CartCoupon; 
use App\Entity\CartProduct; 
use App\Entity\CartCheckout; 
use App\Entity\ProductSponsored; 
use App\Entity\ProductSponsoredCategory; 
use App\Entity\Pricing; 
use App\Entity\City; 
use App\Entity\Region; 
use App\Entity\User; 
use App\Entity\UserShippingLocation; 
use App\Entity\CustomOrder; 
use App\Entity\MaturinOrder; 
use App\Entity\RecurringOrder; 
use App\Entity\DeliveryMethod; 
use App\Entity\DeliveryRoute; 
use App\Entity\Subscription; 
 
use App\Form\CartType; 
use App\Form\CartCheckoutType; 
use App\Form\CustomOrderType; 
 
use App\Service\UserService; 
use App\Service\PaymentService; 
use App\Service\DistributorService; 
use App\Service\CompanyService; 
use App\Service\TwigGlobalVariables; 
use DateTime; 
 
class CartController extends AbstractController 
{ 
 
    private $session; 
 
    public function __construct(SessionInterface $session) 
    { 
        $this->session = $session; 
    } 
    /** 
     * @route("/api/product/payment/add/{id}", 
     *      name="addProductAtPayment") 
     */ 
    public function addProductAtPayment(Product $product, UserService $userServ) 
    { 
        $em = $this->getDoctrine()->getManager(); 
        $this->addToCart($product, 1, $userServ, $em); 
 
        return $this->redirectToRoute('cartPayment'); 
    } 
 
    /** 
     * @route("/api/product/cart/add/{id}", 
     *      name="addProductAtCart") 
     */ 
    public function addProductAtCart(Product $product, UserService $userServ, EntityManagerInterface $em) 
    { 
        $em = $this->getDoctrine()->getManager(); 
        $this->addToCart($product, 1, $userServ, $em); 
 
        return $this->redirectToRoute('viewCart'); 
    } 
 
    /** 
     * @route("/maintenance/fix/recalculateTaxesOfAllPaidsCarts", 
     *      name="calculateCartTaxes") 
     */ 
    public function calculateCartTaxes(PaymentService $paymentServ){ 
        $em = $this->getDoctrine()->getManager(); 
        $carts = $em->getRepository(Cart::class)->findAllPaid(); 
 
        foreach($carts as $cart){ 
            //Coupong is included by default see CartProduct.php method getTotal 
            $taxes = $paymentServ->calculateTaxes($cart->getTotalProductsTaxable(), $cart->getShippingAddress()->getProvince()); 
            $cart->setTaxesProductsCalculations($taxes); 
            $cart->setTaxesProducts($taxes['totalTax']); 
 
            //Taxes shipping if by solex 
            $taxes = $paymentServ->calculateTaxes($cart->getShippingMaturinCost(), $cart->getShippingAddress()->getProvince()); 
            $cart->setTaxesShippingMaturinCalculations($taxes); 
            $cart->setTaxesShippingMaturin($taxes['totalTax']); 
 
            //@TODO Calculate Shipping Company 
            $taxes = $paymentServ->calculateTaxes($cart->getShippingCompanyCost(), $cart->getShippingAddress()->getProvince()); 
            $cart->setTaxesShippingCompanyCalculations($taxes); 
            $cart->setTaxesShippingCompany($taxes['totalTax']); 
 
            // taxes packing 
            $taxes = $paymentServ->calculateTaxes($cart->getPackingCost(), $cart->getShippingAddress()->getProvince()); 
            $cart->setTaxesPackingCalculations($taxes); 
            $cart->setTaxesPacking($taxes['totalTax']); 
 
            $em->persist($cart); 
        } 
        $em->flush(); 
 
        return new Response('Done'); 
    } 
 
    /** 
     * @route({ 
     *          "fr": "/core/convert/cart", 
     *          "en": "/core/convert/cart" 
     *      }, 
     *      name="convertCart") 
     */ 
    public function convertCart(UserService $userServ){ 
        // $userServ->sendEmail('test subject', 'test html', false, 'stephanejourney@gmail.com'); 
        //Disable 
        return false; 
        // 
        // 
        // $em = $this->getDoctrine()->getManager(); 
        // $carts = $em->getRepository(Cart::class)->findAll(); 
        // foreach($carts as $cart){ 
        //     if(count($cart->getMaturinOrders()) < 1 && count($cart->getCustomOrders()) < 1){ 
        //         /* 
        //          * Here we split and populate different Orders 
        //          * those orders are what the Company will see and be billed on 
        //          */ 
        //         $customOrders = array(); 
        //         $maturinOrders = array(); 
        // 
        //         foreach($cart->getProducts() as $p){ 
        //             if($p->getProduct()->isShippedByMaturin()){ 
        // 
        //                 //Let's reduce the quantity of all products while at it only if it's not a JIT product 
        //                 if(!$p->getProduct()->getIsJustInTime()) 
        //                     $p->getProduct()->setQtyReadyToShip($p->getProduct()->getQtyReadyToShip() - $p->getQuantity()); 
        // 
        //                 $em->persist($p->getProduct()); 
        // 
        //                 $cId = $p->getProduct()->getCompany()->getId(); 
        //                 if(empty($maturinOrders[$cId])){ 
        //                     $maturinOrders[$cId] = new MaturinOrder(); 
        //                     $maturinOrders[$cId]->setFromCart($cart); 
        //                     $maturinOrders[$cId]->setCompany($p->getProduct()->getCompany()); 
        //                 } 
        //                 $maturinOrders[$cId]->addItem($p); 
        // 
        //             }else{ 
        //                 /* 
        //                  * For now all orders from custom Delivery as sent into the CustomOrder Entity for easier managing 
        //                  * We regroup them by producer 
        //                  */ 
        //                 $cId = $p->getProduct()->getCompany()->getId(); 
        //                 if(empty($customOrders[$cId])){ 
        //                     $customOrders[$cId] = new CustomOrder(); 
        //                     $customOrders[$cId]->setFromCart($cart); 
        //                     $customOrders[$cId]->setCompany($p->getProduct()->getCompany()); 
        //                 } 
        //                 $customOrders[$cId]->addItem($p); 
        //             } 
        //         } 
        // 
        //         //Now le's save all the Maturin Orders 
        //         foreach($maturinOrders as $c){ 
        //             $em->persist($c); 
        //         } 
        // 
        //         //Now le's save all the customOrders 
        //         foreach($customOrders as $c){ 
        //             $em->persist($c); 
        //         } 
        //     } 
        // } 
        // $em->flush(); 
        // 
        // //$form = $this->createForm(ProductReplenishmentType::class, $replenishment); 
        // return new Response('Cart Converted'); 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/acheteur/commande/annuler/{orderNo}", 
     *          "en": "/buyer/order/cancel/{orderNo}/" 
     *      }, name="cancelOrder", 
     *      options = { "expose" = true }, 
     *  ) 
     * @Security("has_role('ROLE_USER')") 
     * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)") 
     */ 
    public function cancelOrder(Cart $cart, UserService $userServ, PaymentService $paymentServ){ 
        $twigData = array(); 
        $user = $userServ->getUser(); 
        if($cart->getUser() != $user){ 
            $this->addFlash('error', "Vous n'avez pas accès a cette commande"); 
            return $this->redirectToRoute('dashboard'); 
        } 
 
        //Extra safety 
        if(!$cart->showRefundButtonToUser()){ 
            $this->addFlash('error', "Cette commande n'est pas remboursable"); 
            return $this->redirectToRoute('listOrders'); 
        } 
 
        if($paymentServ->refundCart($cart, true)) 
            $this->addFlash('success', "Cette commande a été annulé et remboursé!"); 
        else 
            $this->addFlash('error', "Cette commande n'a pas été remboursé"); 
 
 
        return $this->redirectToRoute('listOrders'); 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/acheteur/commande/voir/{orderNo}/{freshSale}", 
     *          "en": "/buyer/order/see/{orderNo}/{freshSale}" 
     *      }, name="viewOrder", 
     *      options = { "expose" = true }, 
     *      defaults = { 
     *          "freshSale" = false 
     *      } 
     *  ) 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/user/orderView.html.twig") 
     * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)") 
     */ 
    public function viewOrder(Cart $cart, $freshSale, UserService $userServ){ 
        $twigData = array(); 
        $user = $userServ->getUser(); 
        if($cart->getUser() != $user){ 
            $this->addFlash('error', "Vous n'avez pas accès a cette commande"); 
            return $this->redirectToRoute('dashboard'); 
        } 
        $twigData['order'] = $cart; 
        $twigData['freshSale']= $freshSale; 
 
        return $twigData; 
    } 
 
     /** 
     * @Route({ 
     *          "fr": "/acheteur/precommande/voir/{orderNo}/{freshSale}", 
     *          "en": "/buyer/preorder/see/{orderNo}/{freshSale}" 
     *      }, name="viewPreOrder", 
     *      options = { "expose" = true }, 
     *      defaults = { 
     *          "freshSale" = false 
     *      } 
     *  ) 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/user/preOrderView.html.twig") 
     * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)") 
     */ 
    public function viewPreOrder(Cart $cart, $freshSale, UserService $userServ){ 
      $twigData = array(); 
      $user = $userServ->getUser(); 
      if($cart->getUser() != $user){ 
          $this->addFlash('error', "Vous n'avez pas accès a cette commande"); 
          return $this->redirectToRoute('dashboard'); 
      } 
      $twigData['order'] = $cart; 
      $twigData['freshSale']= $freshSale; 
 
      return $twigData; 
  } 
 
    /** 
     * @Route({ 
     *          "fr": "/vendeur/commandes/liste/{id}", 
     *          "en": "/seller/orders/list/{id}", 
     *      }, 
     *      defaults={ 
     *          "id" = false 
     *      }, 
     *      name="companyOrders") 
     * 
     * @Security("has_role('ROLE_ADMIN')") 
     * @Template("admin/company/ordersList.html.twig") 
     */ 
    public function companyOrders(Company $company=null, CompanyService $companyServ, EntityManagerInterface $em, UserService $userServ){ 
        $twigData = array(); 
 
        if(empty($company)){ 
            $user = $userServ->getUser(); 
            $companies = $user->getCompanies(); 
 
            if(count($companies) > 1){ 
                $this->addFlash('error', "Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu"); 
                return $this->redirectToRoute('dashboard'); 
            }else{ 
                $company = $companies->get(0); 
            } 
        } 
 
        if(!$companyServ->allowedToModify($company)){ 
            $this->addFlash('error', "Vous n'avez pas accès a cette commpagnie"); 
            return $this->redirectToRoute('dashboard'); 
        } 
 
        $twigData['orders'] = $company->getCustomOrders(); 
        $twigData['company'] = $company; 
        $twigData['reservedOrders'] = $em->getRepository(CartProduct::class)->findReservedProductsForCompany($company); 
        $twigData['preOrder'] = $em->getRepository(CartProduct::class)->findPreOrderProductForCompany($company); 
 
        return $twigData; 
    } 
 
 
      /** 
     * @Route({ 
     *          "fr": "/vendeur/preCommandes/liste/{id}", 
     *          "en": "/seller/preOrders/list/{id}", 
     *      }, 
     *      defaults={ 
     *          "id" = false 
     *      }, 
     *      name="preCompanyOrders") 
     * 
     * @Security("has_role('ROLE_ADMIN')") 
     * @Template("admin/company/preOrdersList.html.twig") 
     */ 
    public function preCompanyOrders(Company $company=null, CompanyService $companyServ, EntityManagerInterface $em, UserService $userServ){ 
      $twigData = array(); 
 
      if(empty($company)){ 
          $user = $userServ->getUser(); 
          $companies = $user->getCompanies(); 
 
          if(count($companies) > 1){ 
              $this->addFlash('error', "Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu"); 
              return $this->redirectToRoute('dashboard'); 
          }else{ 
              $company = $companies->get(0); 
          } 
      } 
 
      if(!$companyServ->allowedToModify($company)){ 
          $this->addFlash('error', "Vous n'avez pas accès a cette commpagnie"); 
          return $this->redirectToRoute('dashboard'); 
      } 
 
      $twigData['orders'] = $company->getCustomOrders(); 
      $twigData['company'] = $company; 
      $twigData['preOrder'] = $em->getRepository(CartProduct::class)->findPreOrderProductForCompany($company); 
 
      return $twigData; 
  } 
 
 
 
 
 
    /** 
     * @Route({ 
     *          "fr": "/vendeur/commandes/maturin/{orderNo}", 
     *          "en": "/seller/orders/maturin/{orderNo}" 
     *      }, name="viewMaturinOrder") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/company/viewMaturinOrder.html.twig") 
     * @Entity("MaturinOrder", expr="repository.findOneByOrderNo(orderNo)") 
     */ 
    public function viewMaturinOrder (MaturinOrder $order, UserService $userServ, Request $request, CompanyService $companyServ){ 
        //@SECuritY 
        if(!$companyServ->allowedToModify($order->getCompany())){ 
            $this->addFlash('error', "Vous n'avez pas d'accès à cette compagnie."); 
            return $this->redirectToRoute('dashboard'); 
        } 
 
        $twigData = array(); 
        $twigData['order'] = $order; 
 
        return $twigData; 
    } 
 
 
    /** 
     * @Route({ 
     *          "fr": "/vendeur/commandes/independante/{orderNo}", 
     *          "en": "/seller/orders/independant/{orderNo}" 
     *      }, name="viewCustomOrder") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/company/viewCustomOrder.html.twig") 
     * @Entity("CustomOrder", expr="repository.findOneByOrderNo(orderNo)") 
     */ 
    public function viewCustomOrder (CustomOrder $order, UserService $userServ, Request $request, CompanyService $companyServ){ 
 
        //@SECuritY 
        if(!$companyServ->allowedToModify($order->getCompany())){ 
            $this->addFlash('error', "Vous n'avez pas d'accès à cette compagnie."); 
            return $this->redirectToRoute('dashboard'); 
        } 
 
        $twigData = array(); 
        $twigData['order'] = $order; 
 
        $form = $this->createForm(CustomOrderType::class, $order); 
        $twigData['form'] = $form->createView(); 
 
        $form->handleRequest($request); 
        if($form->isSubmitted() && $form->isValid()){ 
            $order->setIsShipped(true); 
            $em = $this->getDoctrine()->getManager(); 
 
            $em->persist($order); 
            $em->flush(); 
 
            //Send email to the customer 
 
            if ($order->getCompany()->getAssociations()->count() == 0){ 
                $email = $this 
                    ->get('twig') 
                    ->render('emails/tracking.html.twig', [ 
                        'order' => $order, 
                        'user' => $order->getFromCart()->getUser() 
                    ]); 
 
                $userServ->sendEmail('Votre livraison est en route', $email, false, $order->getFromCart()->getUser()->getEmail()); 
            } 
 
 
 
            return $this->redirectToRoute('companyOrders', array('id' => $order->getCompany()->getId())); 
        } 
        return $twigData; 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/acheteur/commande/encore/{orderNo}", 
     *          "en": "/buyer/order/again/{orderNo}" 
     *      }, name="orderAgain") 
     * @Security("has_role('ROLE_USER')") 
     */ 
    public function orderAgain(Cart $cart, UserService $userServ){ 
        $em = $this->getDoctrine()->getManager(); 
        $user = $userServ->getUser(); 
 
        //Cloning give issue doing it manually 
        $newCart = new Cart(); 
        foreach($cart->getProducts() as $p){ 
            if($p->getProduct()->isSalable()){ 
                $np = new CartProduct(); 
                $np->setQuantity($p->getQuantity()); 
                $np->setProduct($p->getProduct()); 
                $newCart->addProduct($np); 
            } 
        } 
        $newCart->setUser($user); 
        $newCart->setShippingAddress($cart->getShippingAddress()); 
 
        $user->addCart($newCart); 
 
        $em->persist($newCart); 
        $em->persist($user); 
        $em->flush(); 
 
        return $this->redirectToRoute('viewCart'); 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/acheteur/commandes", 
     *          "en": "/buyer/orders" 
     *      }, name="listOrders") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/ordersList.html.twig") 
     */ 
    public function listOrders(UserService $userServ){ 
        $twigData = array(); 
        $user = $userServ->getUser(); 
        $twigData['orders'] = $user->getPaidOrders(); 
        $twigData['pickUpOrders']=$user->getPaidPickUpOrders(); 
 
        return $twigData; 
    } 
 
  /** 
     * @Route({ 
     *          "fr": "/acheteur/precommandes", 
     *          "en": "/buyer/preorders" 
     *      }, name="preListOrders") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("admin/preOrdersList.html.twig") 
     */ 
    public function preListOrders(UserService $userServ){ 
      $twigData = array(); 
      $user = $userServ->getUser(); 
      $em = $this->getDoctrine()->getManager(); 
      $twigData['listPreOrders'] = $em->getRepository(Cart::class)->findBy(['user'=>$user->getId()],['deliveryChoiceDate' => 'ASC']); 
      $twigData['orders'] = $user->getPaidOrders(); 
      $twigData['pickUpOrders']=$user->getPaidPickUpOrders(); 
 
      return $twigData; 
  } 
 
    /* === moved this to the cart entity === @ 2021/03/16 */ 
    /* 
     * Calculate all the fees and all from Cart 
     */ 
    // public function calculateFees(Cart $cart, PaymentService $paymentServ){ 
    //     $em = $this->getDoctrine()->getManager(); 
    // 
    //     //@NOTE Legacy, those are not used anymore 
    //     //Ok let's start with the Maturin Fees and taxes 
    //     $cart->setMaturinFee(round($cart->getTotalProducts(false , false) * 0.1, 2)); 
    //     $cart->setTaxesMaturin($paymentServ->calculateTaxes($cart->getMaturinFee(), $cart->getShippingAddress()->getProvince(), true)); 
    //     // End Legacy 
    // 
    //     foreach($cart->getProducts() as $item){ 
    //         $item->setPricePaidProduct($item->getTotal(false)); 
    //     } 
    // 
    //     //Coupon is included by default see CartProduct.php method getTotal 
    //     $taxes = $paymentServ->calculateTaxes($cart->getTotalProductsTaxable(), $cart->getShippingAddress()->getProvince()); 
    //     $cart->setTaxesProductsCalculations($taxes); 
    //     $cart->setTaxesProducts($taxes['totalTax']); 
    // 
    //     //Taxes shipping if by solex 
    //     $taxes = $paymentServ->calculateTaxes($cart->getShippingMaturinCost(), $cart->getShippingAddress()->getProvince()); 
    //     $cart->setTaxesShippingMaturinCalculations($taxes); 
    //     $cart->setTaxesShippingMaturin($taxes['totalTax']); 
    // 
    //     //@TODO Calculate Shipping Company 
    //     $taxes = $paymentServ->calculateTaxes($cart->getShippingCompanyCost(), $cart->getShippingAddress()->getProvince()); 
    //     $cart->setTaxesShippingCompanyCalculations($taxes); 
    //     $cart->setTaxesShippingCompany($taxes['totalTax']); 
    // 
    //     // taxes packing 
    //     $taxes = $paymentServ->calculateTaxes($cart->getPackingCost(), $cart->getShippingAddress()->getProvince()); 
    //     $cart->setTaxesPackingCalculations($taxes); 
    //     $cart->setTaxesPacking($taxes['totalTax']); 
    // 
    //     //Estimating Payment Cost 
    // 
    //     $em->persist($cart); 
    //     $em->flush(); 
    // 
    // } 
 
    /** 
     * @Route({ 
     *          "fr": "/payer", 
     *          "en": "/payment" 
     *      }, name="cartPayment") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/payment.html.twig") 
     */ 
    public function cartPayment(Request $request, PaymentService $paymentServ, UserService $userServ, UrlGeneratorInterface $router, DistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){ 
        $twigData = array(); 
        $twigData['hideSideMenu'] = true; 
        // $twigData['loader']= true; 
        $twigData['suggestedProducts']= $userServ->findProductsToSuggest(); 
        $em = $this->getDoctrine()->getManager(); 
        $cart = $userServ->getCart(); 
        // dump($cart->getPickUpAddress()); 
        // if(empty($cart->getShippingAddress()) && empty($cart->getPickUpAddress())){ 
        //     $this->addFlash('error', "Nous avons d'abord besoin d'une adresse de livraison'"); 
        //     return $this->redirectToRoute('checkout'); 
        // } 
        
        /* 
         * Called when there is a Shipping Method change 
         * But not a payment 
         */ 
        if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){ 
            // if(!$cart->hasMaturinShipping()){ 
              if($cart->hasMaturinShipping()){ 
              $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart); 
            } 
 
            //Update the Shipping cost 
            if(!empty($twigData['shippingMaturin'])){ 
              $maturinShipping = current($twigData['shippingMaturin']); 
            } else { 
              $maturinShipping = false; 
            } 
            
 
            $found = false; 
 
            if($maturinShipping){ 
                foreach($twigData['shippingMaturin'] as $s){ 
                    if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){ 
                        $found = true; 
 
                        $cart->setShippingMaturinCost($s->estimatedCost); 
                        $cart->setShippingMaturinCarrierName($s->carrierName); 
                        $cart->setShippingMaturinServiceName($s->serviceName); 
                        $cart->setShippingMaturinServiceId($s->serviceId); 
 
                        if ($cart->getPreOrderNow()){ 
                          $dateDeliveryChoice = $cart->getDeliveryChoiceDate(); 
                          $cart->setShippingMaturinEstimatedDate($dateDeliveryChoice); 
                        } else { 
                        $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart); 
                       //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate)); 
                        $cart->setShippingMaturinEstimatedDate($estimatedCartDate); 
                        } 
                        $twigData['currentShipping'] = $s; 
                        break; 
                    } 
                } 
 
                if(!($request->request->has('maturinShipping') && $found)){ 
 
                    $cart->setShippingMaturinCost($maturinShipping->estimatedCost); 
                    $cart->setShippingMaturinCarrierName($maturinShipping->carrierName); 
                    $cart->setShippingMaturinServiceName($maturinShipping->serviceName); 
                    $cart->setShippingMaturinServiceId($maturinShipping->serviceId); 
 
                    if ($cart->getPreOrderNow()){ 
                      $dateDeliveryChoice = $cart->getDeliveryChoiceDate(); 
                      $cart->setShippingMaturinEstimatedDate($dateDeliveryChoice); 
                    } else { 
 
                    //// old estimate not working anymore for delivery date we change it to new estimation route 
                    $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart); 
                    $maturinShipping->estimatedDate = $estimatedCartDate["date"]; 
                    $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate); 
                    } 
                    //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate)); 
 
                    $twigData['currentShipping'] = $maturinShipping; 
                } 
                $em->persist($cart); 
                $em->flush(); 
            }else{ 
                if($cart->hasMaturinShipping()){ 
                    //Should be an error with the shipping 
                    //In theory the flash should show the error to user 
                    //so we redirect to shipping address 
                    $twigData['noGo'] = true; 
                    return $this->redirectToRoute('checkout'); 
                } 
            } 
        } 
 
        $shippingAddress = $cart->getShippingAddress(); 
        //We need a shipping address for the taxes 
        if($shippingAddress) { 
            $cart->calculateFees(); 
            $em->persist($cart); 
            $em->flush(); 
        } 
        $PuroTest = null; 
        if ($shippingAddress){ 
          $getMethodLivraisons = $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]); 
          foreach ($getMethodLivraisons as $getMethodLivraison) { 
            if ($getMethodLivraison->getType() == 'maturin') 
            $PuroTest = 'maturin'; 
          } 
        } 
        $twigData['puroConfirm'] = $PuroTest; 
 
        /* 
         * If payment is ready 
         */ 
        if($request->request->has('stripeToken') || $request->request->has('use-previous-card')){ 
            if(!empty($request->request->get('stripeToken'))) 
                $cart->setStripeToken($request->request->get('stripeToken')); 
 
                 
                if($request->request->get('NoteFromBuyer')){ 
              $noteFromBuyer = $request->request->get('NoteFromBuyer');  
              if (strlen($noteFromBuyer) <= 100){ 
                $patternNoteFromBuyer = '/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u'; 
                if(preg_match($patternNoteFromBuyer, 
                  $noteFromBuyer 
                )){ 
                   $noteFromBuyer = preg_replace($patternNoteFromBuyer,  
                  '',  
                  $noteFromBuyer); 
                } 
                $cart->setNoteFromBuyer($noteFromBuyer); 
              }else{ 
                $this->addFlash('error', "Veuillez ne pas dépasser les 100 characteres dans votre messages au livreur."); 
                return $this->redirectToRoute('checkout'); 
              } 
            } 
            //Let's save if the signature was asked for the shipping 
            // todo move from here 
            $signature = $request->request->get('signature-required'); 
            if($signature) 
                $cart->setShippingSignatureRequired(true); 
            else 
                $cart->setShippingSignatureRequired(false); 
                
            $em->persist($cart); 
            $em->flush(); 
  /*---------------------------- en dessous insert la condition si champs preorder true alors envoi dans container preorders ---------------------------------------------*/ 
             if($paymentServ->payCart($cart)) { 
 
                $user = $userServ->getUser(); 
 
                $locale = $request->getSession()->get('_locale'); 
                if(empty($locale)) 
                    $locale = 'fr'; 
 
                //if ($cart->getPreOrderNow() != true){ 
                  $newRoute = $router->generate( 'viewOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo())); 
 
                  $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                  $this->addFlash('success', "Votre commande a été passée avec succès"); 
               /* }else{ 
                  $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo())); 
 
                  $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                  $this->addFlash('success', "Votre commande a été passée avec succès"); 
                }*/ 
 
                $emailBody = $this->get('twig')->render('emails/order.html.twig', [ 
                    'cart' => $cart, 
                    'user' => $cart->getUser() 
                ]); 
 
                $replyTo = []; 
                foreach ($cart->getProducts() as $cartProduct) { 
                    if (($association = $cartProduct->getAddedWhenBeingInAssociation()) != null) 
                    { 
                        foreach ($association->getAdminUsers() as $adminUser){ 
                            $replyTo[]=$adminUser->getEmail(); 
                        } 
                        foreach ($association->getUsersAddingCompanies() as $adminUser){ 
                            $replyTo[]=$adminUser->getEmail(); 
                        } 
                    } 
                  } 
 
                $replyTo = count($replyTo) == 0 ? false : array_unique($replyTo); 
 
                $userServ->sendEmail( 
                    'Confirmation de votre commande #'.$cart->getOrderNo(), 
                    $emailBody, 
                    false, 
                    $cart->getUser()->getEmail(), false, null, $replyTo 
                ); 
 
                //This happen if the cart contain JIT product OR the shipping estimate didn'T worked 
                if(!$cart->getPreOrderNow()){ 
                  if(!$cart->getIsOnHold()){ 
                      //We are ready let's send the order 
                      if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){ 
                          $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (hasMaturinShipping):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                      }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){ 
                        $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (isMaturinPickUp):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                      } 
                  } 
                } 
 
                /* 
                 * Let's see if it's the user first order 
                 * In this case, and he got a referrer we give him a coupon 
                 */ 
                if($user->isFirstOrder() && !empty($user->getReferredBy())){ 
                    $coupon = new CartCoupon(); 
                    $coupon->setOneTimeOnly(true); 
                    $coupon->setType(0); 
                    $coupon->setAmount(10); 
                    $coupon->setCode('C-'.uniqid()); 
                    $coupon->setForUser($user->getReferredBy()); 
                    $coupon->setDateFrom(new \DateTime()); 
                    $coupon->setDateTo(new \DateTime("+1 year")); 
                    $em->persist($coupon); 
                } 
 
                //If it's a gift order let's remove the amount on it 
                if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){ 
                    $coupon = $cart->getUsedCoupon(); 
                    $cart->setAmountSavedByCoupon($cart->getCouponSavings()); 
                    $coupon = $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false)); 
 
                    $em->persist($cart); 
                    $em->persist($coupon); 
                } 
 
                $em->flush(); 
 
                if ($shippingAddress) { 
                  $cityName = $shippingAddress->getCity(); 
                  $province = $shippingAddress->getProvince(); 
                  if ($cityName && $province) { 
                    //$city = $em->getRepository(City::class)->findLikeName($cityName); 
                    $city = $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province); 
                    if (empty($city)) { 
                      // $cart->setIsOnHold(true); 
                      $em->persist($cart); 
                      $em->flush(); 
                      $userServ->sendEmail( 
                          'Ville invalide pour la commande #'.$cart->getOrderNo(), 
                          'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(), 
                          false, 
                          "info@maturin.ca", false, null, "info@maturin.ca" 
                      ); 
                    } 
                  } 
                } 
 
                return $this->redirectToRoute('viewOrder', array('orderNo' => $cart->getOrderNo(), 'freshSale' => true)); 
            } else { 
 
                $this->addFlash('error', 'Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.'); 
                return $this->redirectToRoute('cartPayment'); 
            } 
            /* 
                $userServ->addNotification('error', 'Votre commande', 'Une erreur est survenue, veuillez contacter notre support.'); 
                //$this->addFlash('error', "Une erreur est survenue avec votre commande"); 
            } 
             */ 
 
        } 
 
        return $twigData; 
    } 
 
 
    /** 
     * @Route({ 
     *          "fr": "/livraison-groupe-payer", 
     *          "en": "/bulk-shipping-payment" 
     *      }, name="bulkship_payment") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/bulkship.payment.html.twig") 
     */ 
    public function bulkship_payment(UrlGeneratorInterface $router, UserService $userServ, Request $request, PaymentService $paymentServ, DistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService) { 
      $twigData = array(); 
      $twigData['hideSideMenu'] = true; 
      $twigData['loader']= true; 
 
      $em = $this->getDoctrine()->getManager(); 
 
      $user = $userServ->getUser(); 
      $userCart = $userServ->getCart(); 
 
      /* 
       * If payment is ready 
       */ 
      if($request->request->has('stripeToken') || $request->request->has('use-previous-card')) { 
          $carts = []; 
          $_carts = $em->getRepository(Cart::class)->findBy(['isBulkOrder' => true, 'isPaid' => false, 'user' => $user]); 
          foreach($_carts as $cart) { 
            $carts[] = $cart; 
          } 
 
          $signature = $request->request->get('signature-required'); 
 
          $userCart = $userServ->getCart(); 
          $cartCoupon = $userCart->getUsedCoupon(); 
 
          foreach($carts as $cart) { 
            if(!empty($request->request->get('stripeToken'))) { 
              $cart->setStripeToken($request->request->get('stripeToken')); 
            } 
 
            if($signature) { 
              $cart->setShippingSignatureRequired(true); 
            } else { 
              $cart->setShippingSignatureRequired(false); 
            } 
 
            if ($cartCoupon) { 
              $cart->setUsedCoupon($cartCoupon); 
            } 
 
            // if($request->request->get('NoteFromBuyer')){ 
            //   $cart->setNoteFromBuyer($request->request->get('NoteFromBuyer')); 
            // } 
            $cart->setPreOrderNow(false); 
            $cart->setPreOrder(false); 
            $cart->setDeliveryChoiceDate(null); 
         
          $em->persist($cart); 
          $em->flush(); 
             
            $em->persist($cart); 
            $em->flush(); 
          } 
          if($paymentServ->payBulkCarts($carts)){ 
 
              $locale = $request->getSession()->get('_locale'); 
              if(empty($locale)) 
                  $locale = 'fr'; 
 
              $newRoute = $router->generate( 'listOrders' ); 
 
              $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
              $this->addFlash('success', "Votre commande a été passée avec succès"); 
 
              $replyTo = []; 
 
              foreach($carts as $cart) { 
                foreach ($cart->getProducts() as $cartProduct) { 
                  if (($association = $cartProduct->getAddedWhenBeingInAssociation()) != null) 
                  { 
                    foreach ($association->getAdminUsers() as $adminUser){ 
                      $replyTo[]=$adminUser->getEmail(); 
                    } 
                    foreach ($association->getUsersAddingCompanies() as $adminUser){ 
                      $replyTo[]=$adminUser->getEmail(); 
                    } 
                  } 
                } 
                //This happen if the cart contain JIT product OR the shipping estimate didn'T worked 
                if(!$cart->getPreOrderNow()){ 
                  if(!$cart->getIsOnHold()){ 
                  //We are ready let's send the order 
                  if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){ 
                    $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID:'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                  }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){ 
                    $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID:'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                  } 
                } 
              } 
 
                if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){ 
                    $coupon = $cart->getUsedCoupon(); 
                    $cart->setAmountSavedByCoupon($cart->getCouponSavings()); 
                    $coupon = $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false)); 
 
                    $em->persist($cart); 
                    $em->persist($coupon); 
                    $em->flush(); 
                } 
              } 
 
              $emailBody = $this->get('twig')->render('emails/order.bulk.html.twig', [ 
                'carts' => $carts, 
                'user' => $userServ->getUser() 
              ]); 
 
              $replyTo = count($replyTo) == 0 ? false : array_unique($replyTo); 
 
              $userServ->sendEmail( 
                'Confirmation de vos commandes', 
                $emailBody, 
                false, 
                $userServ->getUser()->getEmail(), false, null, $replyTo 
              ); 
 
              // /* 
              //  * Let's see if it's the user first order 
              //  * In this case, and he got a referrer we give him a coupon 
              //  */ 
              // if($user->isFirstOrder() && !empty($user->getReferredBy())){ 
              //     $coupon = new CartCoupon(); 
              //     $coupon->setOneTimeOnly(true); 
              //     $coupon->setType(0); 
              //     $coupon->setAmount(10); 
              //     $coupon->setCode('C-'.uniqid()); 
              //     $coupon->setForUser($user->getReferredBy()); 
              //     $coupon->setDateFrom(new \DateTime()); 
              //     $coupon->setDateTo(new \DateTime("+1 year")); 
              //     $em->persist($coupon); 
              // } 
              // 
              // //If it's a gift order let's remove the amount on it 
 
              $em->remove($userCart); 
              $em->flush(); 
 
              return $this->redirectToRoute('listOrders'); 
          } else { 
              $this->addFlash('error', 'Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.'); 
              return $this->redirectToRoute('bulkship_payment'); 
          } 
      } else { 
 
        /* remove previous carts with unpaid bulk orders */ 
        $carts = $em->getRepository(Cart::class)->findBy(['isBulkOrder' => true, 'isPaid' => false, 'user' => $user]); 
        foreach($carts as $cart) { 
          $em->remove($cart); 
          $em->flush(); 
        } 
 
        $new_carts = []; 
 
        $cart = $userServ->getCart(); 
 
        $warn_qty_adjust = false; 
 
        foreach($cart->getProducts() as $p) { 
          $product_id = $p->getProduct()->getId(); 
          $qty_left = $p->getProduct()->getQtyReadyToShip(); 
 
          $session_imported_rows = $this->session->get('IMPORTED_ROWS_'.$product_id); 
 
          if (!empty($session_imported_rows)) { 
            $session_imported_rows = json_decode($session_imported_rows, true); 
          } 
 
          foreach($session_imported_rows as $row) { 
            $qty = $row["quantity"]; 
            if ($qty > $qty_left) { 
              $qty = $qty_left; 
              $warn_qty_adjust = true; 
            } 
            $qty_left = $qty_left - $qty; 
 
            if ($qty > 0) { 
 
              if (!isset($new_carts[$row["id"]])) { 
                $new_carts[$row["id"]] = new Cart(); 
                $new_carts[$row["id"]]->setUser($user); 
                $UserShippingLocation = $em->getRepository(UserShippingLocation::class)->findOneBy([ 
                  "email" => $row["contact_col_email"], 
                  "name" => $row["contact_col_fullname"], 
                  "user" => $user, 
                ]); 
 
                if (empty($UserShippingLocation)) { 
                  $UserShippingLocation = new UserShippingLocation(); 
                } 
 
                $UserShippingLocation->setName($row["contact_col_fullname"]); 
                $UserShippingLocation->setPhone($row["contact_col_phone"]); 
                $UserShippingLocation->setEmail($row["contact_col_email"]); 
                $UserShippingLocation->setCivicNumber($row["contact_col_civicnb"]); 
                $UserShippingLocation->setStreetName($row["contact_col_streetname"]); 
                $UserShippingLocation->setUnit($row["contact_col_appartment"]); 
                $UserShippingLocation->setCity($row["contact_col_city"]); 
                $UserShippingLocation->setProvince($row["contact_col_province"]); 
                $zipCode = trim(str_replace("-","", str_replace(" ", "", $row["contact_col_zipcode"]))); 
                $UserShippingLocation->setZipCode($zipCode); 
                $UserShippingLocation->setUser($user); 
 
                $em->persist($UserShippingLocation); 
                $em->flush(); 
                $new_carts[$row["id"]]->setShippingAddress($UserShippingLocation); 
 
                $new_carts[$row["id"]]->setIsBulkOrder(true); 
 
              } 
 
              $new_carts[$row["id"]]->setShippingSignatureRequired(false); 
              if (isset($row["signreq"])) { 
                if ($row["signreq"]) { 
                  $new_carts[$row["id"]]->setShippingSignatureRequired(true); 
                } 
              } 
 
              if($p->getProduct()->isSalable()) { 
                $np = new CartProduct(); 
                $np->setProduct($p->getProduct()); 
                $np->setRecurringFrequency($p->getRecurringFrequency()); 
                $np->setQuantity($qty); 
                $new_carts[$row["id"]]->addProduct($np); 
              } 
            } 
          } 
        } 
 
        if ($warn_qty_adjust) { 
          $this->addFlash('warning', "Les quantité ont été ajustées en fonction de l'inventaire."); 
        } 
 
        foreach($new_carts as $newCartId => $newCart) { 
 
          if($newCart->hasMaturinShipping()) 
            $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($newCart); 
 
          //Update the Shipping cost 
          $maturinShipping = false; 
          if (!empty($twigData['shippingMaturin'])) { 
            $maturinShipping = current($twigData['shippingMaturin']); 
          } 
 
          $found = false; 
          $currentShipping = false; 
 
          if($maturinShipping){ 
            $newCart->setShippingMaturinCost($maturinShipping->estimatedCost); 
            $newCart->setShippingMaturinCarrierName($maturinShipping->carrierName); 
            $newCart->setShippingMaturinServiceName($maturinShipping->serviceName); 
            $newCart->setShippingMaturinServiceId($maturinShipping->serviceId); 
            $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($newCart); 
            $maturinShipping->estimatedDate = $estimatedCartDate["date"]; 
            $newCart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate); 
 
            $currentShipping = $maturinShipping; 
          } 
 
          $em->persist($newCart); 
          $em->flush(); 
 
          $cartId = $newCart->getId(); 
 
          if($newCart->getShippingAddress()) { 
            $newCart->calculateFees(); 
            $em->persist($newCart); 
            $em->flush(); 
          } 
 
          $twigData["carts"][] = [ 
            'cart' => $newCart, 
            'currentShipping' => $currentShipping, 
            'shippingMaturin' => $twigData['shippingMaturin'], 
          ]; 
        } 
 
      } 
 
      return $twigData; 
    } 
 
 
    /** 
     * @Route({ 
     *          "fr": "/livraison-groupe", 
     *          "en": "/bulk-shipping" 
     *      }, name="bulkship") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/bulkship.cart.html.twig") 
     */ 
    public function bulkship(UserService $userServ, Request $request) { 
      $twigData = array(); 
      $twigData['hideSideMenu'] = true; 
      $twigData['loader']= true; 
      $em = $this->getDoctrine()->getManager(); 
      $cart = $userServ->getCart(); 
 
        $cart->setPreOrderNow(false); 
        $cart->setPreOrder(false); 
        $cart->setDeliveryChoiceDate(null); 
     
      $em->persist($cart); 
      $em->flush(); 
      $twigData["products"] = []; 
      $products = $cart->getProducts(); 
      foreach($products as $product) { 
        $twigData["products"][$product->getProduct()->getId()] = [ 
          "cart_product" => $product, 
          "ship_to" => [], 
          "default_ship_to" => [$cart->getShippingAddress()], 
          "default_ship_to_email" => $userServ->getUser()->getEmail(), 
          "rows_to_import" => [], 
          "row_to_test_import" => [], 
          "imported_filename" => "", 
          "multiple_ship_to" => false, 
          "file_upload_error" => false, 
          "file_upload_success" => false, 
        ]; 
        $session_imported_rows = $this->session->get('IMPORTED_ROWS_'.$product->getProduct()->getId()); 
        if (!empty($session_imported_rows)) { 
          $twigData["products"][$product->getProduct()->getId()]["ship_to"] = json_decode($session_imported_rows, true); 
          $twigData["products"][$product->getProduct()->getId()]["multiple_ship_to"] = true; 
        } 
      } 
 
      $user = $userServ->getUser(); 
 
      $em = $this->getDoctrine()->getManager(); 
 
      if ($request->isMethod('post')) { 
        
          $posts = $request->request->all(); 
 
          if ($posts["action"] == "delete_form_address") { 
            $product_id = $posts["product_id"]; 
            $contact_email = $posts["contact_email"]; 
 
            foreach($twigData["products"][$product_id]["ship_to"] as $idx=>$ship_to) { 
              if ($ship_to["contact_col_email"] == $contact_email) { 
                unset($twigData["products"][$product_id]["ship_to"][$idx]); 
                $imported_rows = $twigData["products"][$product_id]["ship_to"]; 
                $this->session->set('IMPORTED_ROWS_'.$product_id, json_encode($imported_rows)); 
              } 
            } 
          } 
 
          if ($posts["action"] == "add_new_address") { 
            $product_id = $posts["product_id"]; 
 
            $ship_to = []; 
            $ship_to["quantity"] = 1; 
            $ship_to["contact_col_email"] = $posts["cart_checkout"]["newAddress"]["email"]; 
            $ship_to["contact_col_fullname"] = $posts["cart_checkout"]["newAddress"]["name"]; 
            $ship_to["contact_col_phone"] = $posts["cart_checkout"]["newAddress"]["phone"]; 
            $ship_to["contact_col_civicnb"] = $posts["cart_checkout"]["newAddress"]["civicNumber"]; 
            $ship_to["contact_col_streetname"] = $posts["cart_checkout"]["newAddress"]["streetName"]; 
            $ship_to["contact_col_appartment"] = $posts["cart_checkout"]["newAddress"]["unit"]; 
            $ship_to["contact_col_city"] = $posts["cart_checkout"]["newAddress"]["city"]; 
            $ship_to["contact_col_province"] = $posts["cart_checkout"]["newAddress"]["province"]; 
            $ship_to["contact_col_zipcode"] = $posts["cart_checkout"]["newAddress"]["zipCode"]; 
            $ship_to["contact_col_zipcode"] = str_replace(" ", "", $ship_to["contact_col_zipcode"]); 
            $ship_to["contact_col_zipcode"] = str_replace("-", "", $ship_to["contact_col_zipcode"]); 
            $ship_to["id"] = md5( 
              mb_strtolower($ship_to["contact_col_civicnb"].$ship_to["contact_col_streetname"].$ship_to["contact_col_appartment"].$ship_to["contact_col_zipcode"]) 
            ); 
            if (filter_var($ship_to["contact_col_email"], FILTER_VALIDATE_EMAIL)) { 
              $twigData["products"][$product_id]["ship_to"][] = $ship_to; 
              $imported_rows = $twigData["products"][$product_id]["ship_to"]; 
              $this->session->set('IMPORTED_ROWS_'.$product_id, json_encode($imported_rows)); 
            } else { 
              $twigData["products"][$product_id]['file_upload_error'] = "Le courriel a un format non valide."; 
            } 
          } 
 
          if ($posts["action"] == "process_ship_to") { 
            $errors = false; 
 
            $payload = json_decode($posts["payload"], true); 
 
            foreach($twigData["products"] as $product_id => $product) { 
 
              if ($payload[$product_id]["multiple_ship_to"]) { 
                if (empty($product["ship_to"])) { 
                  $twigData["products"][$product_id]['file_upload_error'] = "Veuillez importer des destinataires dans votre commande."; 
                  $errors = true; 
                } else { 
                  foreach($product["ship_to"] as $_idx => $ship_to) { 
                    $qty = $payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["qty"]; 
                    $signreq = false; 
                    if (isset($payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["signreq"])) { 
                      $signreq = $payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["signreq"]; 
                    } 
                    $twigData["products"][$product_id]["ship_to"][$_idx]["quantity"] = $qty; 
                    $twigData["products"][$product_id]["ship_to"][$_idx]["signreq"] = $signreq; 
                  } 
 
                  $imported_rows = $twigData["products"][$product_id]["ship_to"]; 
                  $this->session->set('IMPORTED_ROWS_'.$product_id, json_encode($imported_rows)); 
                } 
              } else { 
                $ship_to = []; 
                $ship_to["quantity"] = $product["cart_product"]->getQuantity(); 
                $ship_to["contact_col_email"] = $twigData["products"][$product_id]["default_ship_to_email"]; 
                $ship_to["contact_col_fullname"] = $twigData["products"][$product_id]["default_ship_to"][0]->getName(); 
                $ship_to["contact_col_phone"] = $twigData["products"][$product_id]["default_ship_to"][0]->getPhone(); 
                $ship_to["contact_col_civicnb"] = $twigData["products"][$product_id]["default_ship_to"][0]->getCivicNumber(); 
                $ship_to["contact_col_streetname"] = $twigData["products"][$product_id]["default_ship_to"][0]->getStreetName(); 
                $ship_to["contact_col_appartment"] = $twigData["products"][$product_id]["default_ship_to"][0]->getUnit(); 
                $ship_to["contact_col_city"] = $twigData["products"][$product_id]["default_ship_to"][0]->getCity(); 
                $ship_to["contact_col_province"] = $twigData["products"][$product_id]["default_ship_to"][0]->getProvince(); 
                $ship_to["contact_col_zipcode"] = $twigData["products"][$product_id]["default_ship_to"][0]->getZipCode(); 
                $ship_to["contact_col_zipcode"] = str_replace(" ", "", $ship_to["contact_col_zipcode"]); 
                $ship_to["contact_col_zipcode"] = str_replace("-", "", $ship_to["contact_col_zipcode"]); 
                $ship_to["id"] = md5( 
                  mb_strtolower($ship_to["contact_col_civicnb"].$ship_to["contact_col_streetname"].$ship_to["contact_col_appartment"].$ship_to["contact_col_zipcode"]) 
                ); 
                $imported_rows = [$ship_to]; 
                $this->session->set('IMPORTED_ROWS_'.$product_id, json_encode($imported_rows)); 
              } 
 
            } 
 
            if (!$errors) { 
              return $this->redirectToRoute("bulkship_payment"); 
            } 
          } 
 
          if ($posts["action"] == "empty_ship_to") { 
            $imported_rows = []; 
            $twigData["products"][$posts["product_id"]]["ship_to"] = $imported_rows; 
            $twigData["products"][$posts["product_id"]]["multiple_ship_to"] = true; 
            $this->session->set('IMPORTED_ROWS_'.$posts["product_id"], json_encode($imported_rows)); 
          } 
 
          if ($posts["action"] == "import_data") { 
            $configuration = [ 
              "contact_col_fullname" => $posts["contact_col_fullname"], 
              "contact_col_phone" => $posts["contact_col_phone"], 
              "contact_col_email" => $posts["contact_col_email"], 
              "contact_col_civicnb" => $posts["contact_col_civicnb"], 
              "contact_col_streetname" => $posts["contact_col_streetname"], 
              "contact_col_appartment" => $posts["contact_col_appartment"], 
              "contact_col_city" => $posts["contact_col_city"], 
              "contact_col_province" => $posts["contact_col_province"], 
              "contact_col_zipcode" => $posts["contact_col_zipcode"], 
            ]; 
            $ignore_file_header = false; 
            if (isset($posts["ignore_file_header"])) { 
              $ignore_file_header = $posts["ignore_file_header"]; 
            } 
            $session_file_rows_to_be_imported = $this->session->get('ROWS_TO_BE_IMPORTED_'.$posts["product_id"]); 
            $rows = json_decode($session_file_rows_to_be_imported, true); 
            $imported_rows = []; 
 
            $cart_quantity = $twigData["products"][$posts["product_id"]]["cart_product"]->getQuantity(); 
 
            foreach($rows as $idx => $row) { 
              if ($idx == 0 && $ignore_file_header == "on") { 
                continue; 
              } 
              $imported_row = []; 
 
              foreach($configuration as $config_key => $config_value) { 
 
                // strip NON-BREAKING WHITE-SPACES 
                $row[$config_value] = trim(trim($row[$config_value]),chr(0xC2).chr(0xA0)); 
 
                if ($config_key == "contact_col_zipcode") { 
                  $row[$config_value] = str_replace(" ", "", $row[$config_value]); 
                  $row[$config_value] = str_replace("-", "", $row[$config_value]); 
                } 
 
                if ($config_key == "contact_col_fullname") { 
                  $fullname = $row[$config_value]; 
                  $fullname = explode(" ", $fullname); 
                  $fullname_capitalized = ''; 
                  foreach($fullname as $name) { 
                    $fullname_capitalized .= mb_strtoupper(substr($name, 0, 1)).substr($name, 1).' '; 
                  } 
                  $row[$config_value] = $fullname_capitalized; 
                } 
 
                if ($config_key == "contact_col_province") { 
                  /* 
                  'Alberta'=> 'AB', 
                  'Colombie-Britannique' => 'BC', 
                  'Île-du-Prince-Édouard' => 'PE', 
                  'Manitoba' => 'MB', 
                  'Nouveau-Brunswick' => 'NB', 
                  'Nouvelle-Écosse' => 'NS', 
                  'Nunavut' => 'NU', 
                  'Ontario' => 'ON', 
                  'Québec' => 'QC', 
                  'Saskatchewan' => 'SK', 
                  'Terre-Neuve-et-Labrador' => 'NL', 
                  'Territoires du Nord-Ouest' => 'NT', 
                  'Yukon' => 'YT' 
                  */ 
                  $province = $row[$config_value]; 
                  $chars = array( 
                    // Decompositions for Latin-1 Supplement 
                    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', 
                    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', 
                    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', 
                    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', 
                    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', 
                    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', 
                    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', 
                    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', 
                    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', 
                    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', 
                    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', 
                    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', 
                    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', 
                    chr(195).chr(159) => 's', chr(195).chr(160) => 'a', 
                    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', 
                    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', 
                    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', 
                    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', 
                    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', 
                    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', 
                    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', 
                    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', 
                    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', 
                    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', 
                    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', 
                    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', 
                    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', 
                    chr(195).chr(191) => 'y', 
                    // Decompositions for Latin Extended-A 
                    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', 
                    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', 
                    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', 
                    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', 
                    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', 
                    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', 
                    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', 
                    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', 
                    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', 
                    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', 
                    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', 
                    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', 
                    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', 
                    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', 
                    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', 
                    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', 
                    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', 
                    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', 
                    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', 
                    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', 
                    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', 
                    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', 
                    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', 
                    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', 
                    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', 
                    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', 
                    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', 
                    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', 
                    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', 
                    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', 
                    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', 
                    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', 
                    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', 
                    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', 
                    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', 
                    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', 
                    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', 
                    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', 
                    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', 
                    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', 
                    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', 
                    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', 
                    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', 
                    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', 
                    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', 
                    chr(197).chr(154) => 'S',chr(197).chr(155) => 's', 
                    chr(197).chr(156) => 'S',chr(197).chr(157) => 's', 
                    chr(197).chr(158) => 'S',chr(197).chr(159) => 's', 
                    chr(197).chr(160) => 'S', chr(197).chr(161) => 's', 
                    chr(197).chr(162) => 'T', chr(197).chr(163) => 't', 
                    chr(197).chr(164) => 'T', chr(197).chr(165) => 't', 
                    chr(197).chr(166) => 'T', chr(197).chr(167) => 't', 
                    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', 
                    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', 
                    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', 
                    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', 
                    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', 
                    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', 
                    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', 
                    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', 
                    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', 
                    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', 
                    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', 
                    chr(197).chr(190) => 'z', chr(197).chr(191) => 's' 
                  ); 
 
                  $province = strtr($province, $chars); 
                  $province = str_replace("-", "", $province); 
                  $province = str_replace(" ", "", $province); 
 
                  if ( 
                    mb_strtolower($province) == "alberta" || 
                    mb_strtolower($province) == "ab" 
                  ) { 
                    $province = "AB"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "colombiebritannique" || 
                    mb_strtolower($province) == "britishcolumbia" || 
                    mb_strtolower($province) == "bc" 
                  ) { 
                    $province = "BC"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "ileduprinceedouard" || 
                    mb_strtolower($province) == "pe" 
                  ) { 
                    $province = "PE"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "manitoba" || 
                    mb_strtolower($province) == "mb" 
                  ) { 
                    $province = "MB"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "nouveaubrunswick" || 
                    mb_strtolower($province) == "newbrunswick" || 
                    mb_strtolower($province) == "nb" 
                  ) { 
                    $province = "NB"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "nouvelleecosse" || 
                    mb_strtolower($province) == "novascotia" || 
                    mb_strtolower($province) == "ne" || 
                    mb_strtolower($province) == "ns" 
                  ) { 
                    $province = "NS"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "nunavut" || 
                    mb_strtolower($province) == "nu" 
                  ) { 
                    $province = "NU"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "ontario" || 
                    mb_strtolower($province) == "on" 
                  ) { 
                    $province = "ON"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "quebec" || 
                    mb_strtolower($province) == "que" || 
                    mb_strtolower($province) == "qc" 
                  ) { 
                    $province = "QC"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "saskatchewan" || 
                    mb_strtolower($province) == "sk" 
                  ) { 
                    $province = "SK"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "territoiresdunordouest" || 
                    mb_strtolower($province) == "northwestterritories" || 
                    mb_strtolower($province) == "nt" 
                  ) { 
                    $province = "NT"; 
                  } 
                  if ( 
                    mb_strtolower($province) == "yukon" || 
                    mb_strtolower($province) == "yt" 
                  ) { 
                    $province = "YT"; 
                  } 
                  $row[$config_value] = $province; 
                } 
 
 
                $imported_row[$config_key] = $row[$config_value]; 
              } 
 
              $imported_row["contact_col_email"] = trim(trim($imported_row["contact_col_email"]),chr(0xC2).chr(0xA0)); 
              if (filter_var($imported_row["contact_col_email"], FILTER_VALIDATE_EMAIL)) { 
 
                $imported_row["id"] = md5( 
                  mb_strtolower($imported_row["contact_col_civicnb"].$imported_row["contact_col_streetname"].$imported_row["contact_col_appartment"].$imported_row["contact_col_zipcode"]) 
                ); 
 
                $imported_row["quantity"] = 1; 
                $imported_rows[] = $imported_row; 
 
              } else { 
                $imported_rows = []; 
                $twigData["products"][$posts["product_id"]]['file_upload_error'] = "La colonne des courriels contient des courriels qui ont un format non valide. Veuillez vérifier la configuration du fichier."; 
                break; 
              } 
            } 
 
            $twigData["products"][$posts["product_id"]]["ship_to"] = $imported_rows; 
            $twigData["products"][$posts["product_id"]]["multiple_ship_to"] = true; 
            $this->session->set('IMPORTED_ROWS_'.$posts["product_id"], json_encode($imported_rows)); 
          } 
 
          if ($posts["action"] == "import_shipping_addresses") { 
            $tmpfile = $_FILES["fileToUpload"]["tmp_name"]; 
            if (file_exists($tmpfile)) { 
              $filename = basename($_FILES["fileToUpload"]["name"]); 
 
              $path_parts = pathinfo($filename); 
              if (!isset($path_parts['extension'])) { 
                $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Le fichier n'est pas supporté. Veuillez importer un fichier CSV ou Excel (.xls ou .xslx) seulement."; 
              } else { 
                $extension = $path_parts['extension']; 
                if (strtolower($extension) == "xls" || strtolower($extension) == "xlsx" || strtolower($extension) == "csv") { 
                  $rows = []; 
 
                  if (strtolower($extension) == "xls") { 
                    $xls = \SimpleXLS::parse($tmpfile); 
                    if ($xls) { 
                      $rows = $xls->rows(); 
                    } else { 
                      $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Une erreur est survenue, impossible d'interpréter ce document."; 
                    } 
                  } 
 
                  if (strtolower($extension) == "xlsx") { 
                    $xlsx = \SimpleXLSX::parse($tmpfile); 
                    if ($xlsx) { 
                      $rows = $xlsx->rows(); 
                    } else { 
                      $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Une erreur est survenue, impossible d'interpréter ce document."; 
                    } 
                  } 
 
                  if (strtolower($extension) == "csv") { 
                    ini_set('auto_detect_line_endings',TRUE); 
                    if (($handle = fopen($tmpfile, "r")) !== FALSE) { 
                      while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { 
                        if (count($data) > 1) { 
                          $rows[] = $data; 
                        } 
                      } 
                      fclose($handle); 
                    } 
                    if (empty($rows)) { 
                      if (($handle = fopen($tmpfile, "r")) !== FALSE) { 
                        while (($data = fgetcsv($handle, 0, ";")) !== FALSE) { 
                          if (count($data) > 1) { 
                            $rows[] = $data; 
                          } 
                        } 
                        fclose($handle); 
                      } 
                    } 
                    ini_set('auto_detect_line_endings',FALSE); 
                  } 
 
                  if (!empty($rows)) { 
                    $twigData["products"][$posts["product_id"]]["imported_filename"] = $filename; 
                    $twigData["products"][$posts["product_id"]]["row_to_test_import"] = $rows[0]; 
                    $this->session->set('ROWS_TO_BE_IMPORTED_'.$posts["product_id"], json_encode($rows)); 
                  } 
 
                  $twigData["products"][$posts["product_id"]]['file_upload_success'] = "Le fichier a été reçu. Veuillez configurer les colonnes à importer."; 
                } else { 
                  $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Le fichier n'est pas supporté. Veuillez importer un fichier CSV ou Excel seulement."; 
                } 
              } 
              unlink($tmpfile); 
            } else { 
              $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Veuillez importer un fichier CSV ou Excel seulement."; 
            } 
         
          } 
      } 
       
      try { 
        $payload = []; 
        foreach($twigData["products"] as $product_id => $product) { 
          $payload[$product_id]["multiple_ship_to"] = $product["multiple_ship_to"]; 
          if (!empty($product["ship_to"])) { 
            foreach($product["ship_to"] as $address) { 
              $payload[$product_id]["ship_to"][$address["contact_col_email"]]["qty"] = $address["quantity"]; 
            } 
          } 
        } 
        $twigData["ship_to_form_payload"] = json_encode($payload); 
 
      } catch (\Exception $e) { 
          $this->userServ->sendEmail('ERROR: importDataMultipleAdress () failed!', '<p>ERROR: importDataMultipleAdress() failed!</p><p>Impossible to import adress from the form or the file</p><hr/>'.$e->getMessage(), false, 'entrepot@maturin.ca'); 
          $this->addFlash('error', "Une erreur est survenu lors du chargement veuillez vérifier les informations rentrer ou contacter notre support."); 
          return $this->redirectToRoute("bulkship"); 
      } 
 
      return $twigData; 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/deliveryEstimateAjax", 
     *          "en": "/deliveryEstimateAjax" 
     *      }, name="deliveryEstimateAjax") 
     * @Security("has_role('ROLE_USER')") 
     */ 
    public function deliveryEstimateAjax(Request $request, EntityManagerInterface $em, UserService $userServ,TwigGlobalVariables $twigGlobalVariables) { 
 
      $shippingAddressId = trim($request->get("shippingAddressId")); 
      $newAddressProvince = trim($request->get("newAddressProvince")); 
      $shippingAddressCity = trim($request->get("shippingAddressCity")); 
      $user = $userServ->getUser(); 
      $cart = $userServ->getCart(); 
      $city = false; 
  
      if ($shippingAddressId > 0) { 
          $shippingAddress = $em->getRepository(UserShippingLocation::class)->findOneBy(['id'=>$shippingAddressId]); 
          
          if ($shippingAddress) { 
            $city = $shippingAddress->getCity(); 
            $newAddressProvince = $shippingAddress->getProvince(); 
          } 
      }else{ 
          $shippingAddress = $em->getRepository(City::class)->findBy(['id'=>$shippingAddressCity]); 
          foreach ($shippingAddress as $shippingAddressName) { 
            $city = $shippingAddressName->getName(); 
            $newAddressProvince = $shippingAddressName->getProvince(); 
          } 
      } 
 
      if ( $newAddressProvince == "QC" || $newAddressProvince == "ON") { 
        
    } else { 
        $city = $shippingAddressCity; 
    } 
    
      $dow = false; 
      $nameRoute = null; 
      $idRoute = null; 
      if ($city) { 
        $city = trim($city); 
        $cityEntity = $em->getRepository(City::class)->findLikeNameAndProvince($city, $newAddressProvince); 
        $route = $twigGlobalVariables->getEstimationShippingRouteForMaturinProducts($cart, $city); 
        $dateRoute = $route['date']->format('d F Y'); 
 
        if ($cityEntity) { 
 
          $cityEntity = current($cityEntity); 
 
          $cityDeliveryRoutes = $cityEntity->getDeliveryRoutes(); 
 
          foreach($cityDeliveryRoutes as $route) { 
            if ($route->getType() == "maturin") { 
              $nameRoute = $route->getName(); 
              $idRoute = $route->getId(); 
              if ($route->getMonday()) { 
                $dow = 1; 
              } 
              if ($route->getTuesday()) { 
                $dow = 2; 
              } 
              if ($route->getWednesday()) { 
                $dow = 3; 
              } 
              if ($route->getThursday()) { 
                $dow = 4; 
              } 
              if ($route->getFriday()) { 
                $dow = 5; 
              } 
              if ($route->getSaturday()) { 
                $dow = 6; 
              } 
              if ($route->getSunday()) { 
                $dow = 0; 
              } 
            } 
          } 
        } 
      } 
 
      die(json_encode([ 
        'dow' => $dow, 
        'city' => $city, 
        'route' => $dateRoute, 
        'nameRoute' => $nameRoute, 
        'idRoute' => $idRoute 
      ])); 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/newDeliveryEstimateAjax", 
     *          "en": "/newDeliveryEstimateAjax" 
     *      }, name="newDeliveryEstimateAjax") 
     * @Security("has_role('ROLE_USER')") 
     */ 
    public function newDeliveryEstimateAjax(Request $request, EntityManagerInterface $em, UserService $userServ,TwigGlobalVariables $twigGlobalVariables) { 
      $cart = $userServ->getCart(); 
      if ($cart->getShippingAddress()){ 
        $shippingAddressId = $cart->getShippingAddress()->getId(); 
        $shippingAddressCity = $cart->getShippingAddress()->getCity(); 
        $shippingAddressCity= $cart->getShippingAddress()->getProvince();; 
      } 
      $user = $userServ->getUser(); 
      $cart = $userServ->getCart(); 
      $city = false; 
  
      if ($shippingAddressId > 0) { 
          $shippingAddress = $em->getRepository(UserShippingLocation::class)->findOneBy(['id'=>$shippingAddressId]); 
          
          if ($shippingAddress) { 
            $city = $shippingAddress->getCity(); 
            $newAddressProvince = $shippingAddress->getProvince(); 
          } 
      }else{ 
          $shippingAddress = $em->getRepository(City::class)->findBy(['id'=>$shippingAddressCity]); 
          foreach ($shippingAddress as $shippingAddressName) { 
            $city = $shippingAddressName->getName(); 
            $newAddressProvince = $shippingAddressName->getProvince(); 
          } 
      } 
 
      if ( $newAddressProvince == "QC" || $newAddressProvince == "ON") { 
        
    } else { 
        $city = $shippingAddressCity; 
    } 
    
      $dow = false; 
      $nameRoute = null; 
      $idRoute = null; 
      if ($city) { 
        $city = trim($city); 
        $cityEntity = $em->getRepository(City::class)->findLikeNameAndProvince($city, $newAddressProvince); 
        $route = $twigGlobalVariables->getEstimationShippingRouteForMaturinProducts($cart, $city); 
        $dateRoute = $route['date']->format('d F Y'); 
 
        if ($cityEntity) { 
 
          $cityEntity = current($cityEntity); 
 
          $cityDeliveryRoutes = $cityEntity->getDeliveryRoutes(); 
 
          foreach($cityDeliveryRoutes as $route) { 
            if ($route->getType() == "maturin") { 
              $nameRoute = $route->getName(); 
              $idRoute = $route->getId(); 
              if ($route->getMonday()) { 
                $dow = 1; 
              } 
              if ($route->getTuesday()) { 
                $dow = 2; 
              } 
              if ($route->getWednesday()) { 
                $dow = 3; 
              } 
              if ($route->getThursday()) { 
                $dow = 4; 
              } 
              if ($route->getFriday()) { 
                $dow = 5; 
              } 
              if ($route->getSaturday()) { 
                $dow = 6; 
              } 
              if ($route->getSunday()) { 
                $dow = 0; 
              } 
            } 
          } 
        } 
      } 
 
      die(json_encode([ 
        'dow' => $dow, 
        'city' => $city, 
        'route' => $dateRoute, 
        'nameRoute' => $nameRoute, 
        'idRoute' => $idRoute 
      ])); 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/livraison", 
     *          "en": "/delivery" 
     *      }, name="checkout") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/checkout.html.twig") 
     */ 
    public function checkout(UserService $userServ, Request $request,TwigGlobalVariables $twigGlobalVariables){ 
       
      $twigData = array(); 
        $twigData['hideSideMenu'] = true; 
        $twigData['loader']= true; 
        $cart = $userServ->getCart(); 
        $cart->getProducts(); 
        $em = $this->getDoctrine()->getManager(); 
        
        $twigData["products"] = []; 
        $products = $cart->getProducts(); 
        foreach($products as $product) { 
          $twigData["products"][$product->getProduct()->getId()] = [ 
            "cart_product" => $product, 
            "ship_to" => [], 
            "default_ship_to" => [$cart->getShippingAddress()], 
            "default_ship_to_email" => $userServ->getUser()->getEmail(), 
            "rows_to_import" => [], 
            "row_to_test_import" => [], 
            "imported_filename" => "", 
            "multiple_ship_to" => false, 
            "file_upload_error" => false, 
            "file_upload_success" => false, 
          ]; 
          $session_imported_rows = $this->session->get('IMPORTED_ROWS_'.$product->getProduct()->getId()); 
          if (!empty($session_imported_rows)) { 
            $twigData["products"][$product->getProduct()->getId()]["ship_to"] = json_decode($session_imported_rows, true); 
            $twigData["products"][$product->getProduct()->getId()]["multiple_ship_to"] = true; 
          } 
        } 
        $payload = []; 
        foreach($twigData["products"] as $product_id => $product) { 
          $payload[$product_id]["multiple_ship_to"] = $product["multiple_ship_to"]; 
          if (!empty($product["ship_to"])) { 
            foreach($product["ship_to"] as $address) { 
              $payload[$product_id]["ship_to"][$address["contact_col_email"]]["qty"] = $address["quantity"]; 
            } 
          } 
        } 
        $twigData["ship_to_form_payload"] = json_encode($payload); 
        $twigData["pickupLocation"] = $twigGlobalVariables->getGlobalPickUpLocations(); 
        $twigData['checkout'] = $cart; 
        $twigData['activeSubscriptions'] = $userServ->getUser()->getActiveSubscriptions(); 
 
        $contains_alcohol = false; 
        $contains_puro_exclusion = false; 
        $cold_products = false; 
        $products = []; 
 
        foreach($cart->getProducts() as $cp) { 
          $product = $cp->getProduct(); 
          if($product->getIsBoxOfProducts()) { 
            foreach($product->getProductsInBox() as $mp) { 
              $products[] = $mp->getProduct(); 
              if ($mp->getProduct()->getPuroExclusion()) { 
                $contains_puro_exclusion = true; 
              } 
            } 
          } else { 
            $products[] = $product; 
            if ($product->getPuroExclusion()) { 
              $contains_puro_exclusion = true; 
            } 
            if ($product->getId() == 6472) { 
              $contains_puro_exclusion = true; 
            } 
          } 
        } 
        $estimationDateToTake = $cart->getShippingMaturinEstimatedDate(); 
        foreach($products as $product) { 
 
          if ($product->getIsCold()) { 
            $cold_products = true; 
          } 
 
          if ($product->getIsAlcohol()) { 
            $contains_alcohol = true; 
          } 
        } 
        $twigData['contains_alcohol'] = $contains_alcohol; 
         
        if ($request->getMethod() == 'POST'){ 
      //  if($request->get("action") == "proceed_to_payment"){ 
 
            $em = $this->getDoctrine()->getManager(); 
 
            $customDeliveryDate = $request->get("livraisonDate"); 
            if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) { 
              // dump($request->request->get("livraisonDate")) 
              $months = [ 
                'janvier' => 'january', 
                'février' => 'february', 
                'mars' => 'march', 
                'avril' => 'april', 
                'mai' => 'may', 
                'juin' => 'june', 
                'juillet' => 'july', 
                'août' => 'august', 
                'septembre' => 'september', 
                'octobre' => 'october', 
                'novembre' => 'november', 
                'décembre' => 'december' 
              ]; 
 
              $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3]; 
              $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate))); 
 
              $date = new \DateTime('now'); 
              $date->modify('+8 days'); 
 
              if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){ 
                $cart->setDeliveryChoiceDate($requestDate); 
                $cart->setPreOrder(true); 
                $cart->setPreOrderNow(true); 
              }else{ 
                $cart->setDeliveryChoiceDate($requestDate); 
                $cart->setPreOrder(true); 
              } 
            } else { 
                $cart->setPreOrder(false); 
                $cart->setPreOrderNow(false); 
                $cart->setDeliveryChoiceDate(null); 
            } 
 
            $forceRedirect=false; 
            $claudia = $em->getRepository(User::class)->findOneBy(["email" => "corpo@maturin.ca"])->getEmail(); 
 
            if ($this->getUser() && $this->getUser()->getEmail() == $claudia){ 
            }else{ 
            // si il n'y a pas de date de livraison choisi = pas de précommandes donc calcul normal 
           if ($cart->getPreOrder() != false){ 
                //Check if all Maturin product has quantit 
               
            $limit_date = new Datetime('+ 7 days'); 
              foreach($cart->getProducts() as $p){ 
                if ($p->getRecurringFrequency() > 0 && $cart->getDeliveryChoiceDate() >= $limit_date) { 
                    $this->addFlash('error', "Vous ne pouvez pas précommander un abonnement. Veuillez passer votre abonnement en dehors de votre précommande."); 
                    return $this->redirectToRoute('viewCart'); 
                } 
              } 
            } 
          } 
          if ($request->get("action_shipping") == "domicile"){ 
 
            try{ 
            if($request->get("checkoutAddressSelection") == "none"){ 
 
                $newadresseAutocomplete = $request->request->get('newAddress_autocomplete'); 
              
                $pattern = '/\d+/'; 
                preg_match($pattern, $newadresseAutocomplete, $civicnumber); 
                $pattern = strlen($civicnumber[0]); 
                $streetname = substr($newadresseAutocomplete, $pattern); 
                $arrayAutocomplete = explode(', ', trim($streetname)); 
               
                  $newAddress_civicnumber = $civicnumber[0]; 
                  $newAddress_streetname = $arrayAutocomplete[0]; 
                  $newAddress_phone = $request->request->get('newAddress_phone'); 
                  $newAddress_province = $request->request->get('adresse_province'); 
                  $newAddress_zipcode =  $request->request->get('newAddress_zipcode'); 
                  $adresse_unit = $request->request->get('newAddress_unit'); 
                  $newAddress_city = $request->request->get('adresse_city'); 
                  $newAdresse_name =  $request->request->get('newAddress_name'); 
           
                  $findTheCity = $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]); 
       
                  if ($findTheCity == null && $newAddress_province == "QC"){ 
                    $findTheCity = new City(); 
 
                    $findTheCity->setName(trim($newAddress_city)); 
                    $findTheCity->setMrc(trim($newAddress_city)); 
                    $findTheCity->setProvince(trim($newAddress_province)); 
 
                    $findTheRegion = $em->getRepository(Region::class)->findBy(["name"=>'defaut']); 
                    $findTheCity->setRegion($findTheRegion[0]); 
 
                    $em->persist($findTheCity); 
                    $em->flush(); 
 
                    $charlie = $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail(); 
                    $userServ->sendEmail('Une nouvelle ville a été ajouté', '<p>La ville ,' . $newAddress_city . ' a été ajouté dans la base de données par ' . $this->getUser()->getEmail() . '</p>', false, $charlie); 
                  } 
           
                  $UserShippingLocation = new UserShippingLocation(); 
                 
                  $UserShippingLocation->setName($newAdresse_name); 
                    // ajout de condition format et correspond au type de data attendu  
                  $UserShippingLocation->setPhone($newAddress_phone); 
                  $UserShippingLocation->setCivicNumber($newAddress_civicnumber); 
                  $UserShippingLocation->setStreetName($newAddress_streetname); 
                  $UserShippingLocation->setUnit($adresse_unit); 
                  $UserShippingLocation->setCity($newAddress_city); 
                  $UserShippingLocation->setZipCode($newAddress_zipcode); 
                  $UserShippingLocation->setProvince($newAddress_province); 
                  $UserShippingLocation->setUser($this->getUser()); 
                  $UserShippingLocation->setEmail($this->getUser()->getEmail()); 
 
                  $em->persist($UserShippingLocation); 
                  $cart->setShippingAddress($UserShippingLocation); 
                  $em->persist($cart); 
                  $em->flush(); 
            } else { 
              $shippingAddressId = $request->get("checkoutAddressSelection"); 
              $addr = $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]); 
              $addr->setEmail($this->getUser()->getEmail()); 
              $cart->setShippingAddress($addr); 
              $em->persist($cart); 
              $em->flush(); 
            } 
 
          }catch(\Exception $e){ 
            // $this->userServ->sendEmail('ERROR: errorChackoutErrorData() failed!', '<p>ERROR: errorChackoutErrorData() failed!</p><p>Error during save data in database !</p><hr/>'.$e->getMessage(), false, 'entrepot@maturin.ca'); 
            $this->addFlash('error', "Votre adresse comporte une erreur vérifier vos informations"); 
            return $this->redirectToRoute('checkout'); 
          } 
        } 
            /* 
 
              prevent user from using invalid city names 
 
            */ 
            $addr = $cart->getShippingAddress(); 
            if ($request->get('pickupScheduleCheckbox') != "cueillette" ) { 
              if ($addr){ 
                if($addr->getProvince() == 'QC' || $addr->getProvince() == 'ON'){ 
                  if (!$addr->isCityValid()) { 
                    $this->addFlash('error', "Votre adresse de livraison n'est pas valide, veuillez vérifier le nom de la ville."); 
                    return $this->redirectToRoute('checkout'); 
                  } 
                } 
              }elseif(!$addr){ 
                  $shippingAddressId = $request->get("checkoutAddressSelection"); 
                  $addr = $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]); 
                  $cart->setShippingAddress($addr); 
                  $em->persist($cart); 
                  $em->flush(); 
              } 
           } 
            if ($contains_alcohol && $request->get("18YearsOld") != "on") { 
              $this->addFlash('error', "Vous devez certifier que vous avez 18 ans et plus car cette commande contient des produits alcoolisés."); 
              return $this->redirectToRoute('checkout'); 
            } 
 
            $redirect = true; 
            $route_is_puro_nocold = false; 
            $maturin_type_route_found = false; 
            $shippingAddress = $cart->getShippingAddress(); 
 
            if (!$shippingAddress && $request->get('pickupScheduleCheckbox') != "cueillette") { 
          
              $this->addFlash('error', "Votre adresse de livraison n'est pas valide, veuillez vérifier vos informations."); 
              return $this->redirectToRoute('checkout'); 
            } 
 
            if ($shippingAddress) { 
              $cityName = $shippingAddress->getCity(); 
              $province = $shippingAddress->getProvince(); 
              //$city = $em->getRepository(City::class)->findLikeName($cityName); 
              $city = $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province); 
 
              if (empty($city)) { 
                $maturin_type_route_found = true; 
              } else { 
                $city = $city[0]; 
              } 
 
              if ($city) { 
                $routes = $city->getDeliveryRoutes(); 
                foreach($routes as $route) { 
                  if ( 
                    $route->getType() == "maturin" && $route->getName() != "Pas de frais" 
                  ) { 
                    $maturin_type_route_found = true; 
                  } 
                  if ($route->getName() == "Pas de frais") { 
                    $route_is_puro_nocold = true; 
                  } 
                } 
              } 
 
            } 
            $redirect_params = []; 
            if ($contains_puro_exclusion && !$maturin_type_route_found) { 
              // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool."); 
              $redirect_params["alert_nodelivery_puro"] = "true"; 
            } 
 
            if ($contains_alcohol && !$maturin_type_route_found) { 
              // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool."); 
              $redirect_params["alert_nodelivery_alcohol"] = "true"; 
            } 
 
            if ($route_is_puro_nocold && $cold_products && !$maturin_type_route_found) { 
              // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il doit rester frais durant la livraison."); 
              $redirect_params["alert_nodelivery_cold"] = "true"; 
            } 
 
            if (!empty($redirect_params) and $request->get('pickupScheduleCheckbox') != "cueillette" ) { 
              return $this->redirectToRoute('viewCart', $redirect_params); 
            } 
 
            //Lets start with the coupon see if it's valid 
            $coupon = $request->get("coupon"); 
            if(!empty($coupon) ){ 
              $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
              $couponSearchTuango = false; 
              $couponSearchTuango =  $this->CouponTuango($coupon); 
              $couponCabane = false; 
              $couponCabane =  $this->CouponCabaneMaturin($coupon); 
 
              if ($couponSearchTuango != false || $couponCabane != false){ 
                $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
              } 
                if(empty($cartCoupon)){ 
                  if ($couponSearchTuango == false && $couponCabane == false){ 
                    $this->addFlash('error', "Merci de vérifier votre code coupon ou associez-le au bon produit"); 
                    return $this->redirectToRoute('checkout'); 
                  } 
                }else{ 
                    //If coupon is a onetimeonly and was already used 
                    if($cartCoupon->getOneTimeOnly()){ 
                        if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){ 
                            $this->addFlash('error', "Vous avez déja utilisé ce coupon"); 
                            return $this->redirectToRoute('checkout'); 
                        } 
                    } 
                    //Check if any money left 
                    if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= 0 ){ 
                        $this->addFlash('error', "Ce coupon a un solde restant de 0$"); 
                        return $this->redirectToRoute('checkout'); 
                    } 
                    $cart->setUsedCoupon($cartCoupon); 
                    //$user = $userServ->getUser(); 
                    //$user->addCouponUsed($cartCoupon); 
                    //$em->persist($user); 
                } 
            }else{ 
              //$user->removeCouponUsed($cartCoupon); 
              $cart->setUsedCoupon(null); 
            } 
            // picking and packing 
            foreach ($cart->getProducts() as $cp){ 
                if ($request->get('pickupScheduleCheckbox') == "cueillette" ) { 
                  $customDeliveryDate = $request->get("pickupSchedule"); 
                  if (!empty($customDeliveryDate)) { 
                    // dump($request->request->get("livraisonDate")) 
                    $months = [ 
                      'janvier' => 'january', 
                      'février' => 'february', 
                      'mars' => 'march', 
                      'avril' => 'april', 
                      'mai' => 'may', 
                      'juin' => 'june', 
                      'juillet' => 'july', 
                      'août' => 'august', 
                      'septembre' => 'september', 
                      'octobre' => 'october', 
                      'novembre' => 'november', 
                      'décembre' => 'december' 
                    ]; 
       
                    $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3]; 
                    $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate))); 
       
                    $date = new \DateTime('now'); 
                    $date->modify('+8 days'); 
       
                    if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){ 
                      $cart->setDeliveryChoiceDate($requestDate); 
                      $cart->setPreOrder(true); 
                      $cart->setPreOrderNow(true); 
                    }else{ 
                      $cart->setDeliveryChoiceDate($requestDate); 
                      $cart->setPreOrder(true); 
                    } 
                  } else { 
                      $cart->setPreOrder(false); 
                      $cart->setPreOrderNow(false); 
                      $cart->setDeliveryChoiceDate(null); 
                  } 
                  if(!$cp->getProduct()->isShippedByMaturin()){ 
                    $this->addFlash('error', "Le produit ".$cp->getProduct()->getName()." n'est pas disponible pour une cueillette vous devez l'enlever de votre panier afin de procéder"); 
                    return $this->redirectToRoute('viewCart'); 
                  } 
 
                  $pickUpSchedule = $request->get('pickupSchedule'); 
                  if (empty($pickUpSchedule)) { 
                    $this->addFlash('error', "Il faut spécifier une date et un temps de cueillette."); 
                    return $this->redirectToRoute('checkout'); 
                  } 
                  $pickUpAdress = $request->get('pickupLocation'); 
                  $pickupLocationId = $request->get('pickupLocations'); 
 
                  $dm = new DeliveryMethod(); 
                  $dm->setAverageDays(1); 
                  $dm->setIsAPickup(true); 
                  $dm->setServiceId(9999); 
                  $dm->setFixedPrice(0); 
                  $dm->setValid(true); 
                  $dm->setPickupSchedule($pickUpSchedule); 
                  $dm->setPickupAddress($pickUpAdress); 
                  $dm->setPickupLocationId($pickupLocationId); 
                  $cp->setCompanyDeliveryMethod($dm); 
                  $em->persist($dm); 
                  $em->persist($cp); 
                }else { 
                  $dm = $cp->getCompanyDeliveryMethod(); 
                  if($cp->getAddedWhenBeingInAssociation()){ 
                    if($cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.canPickUp')){ 
                      $dm = new DeliveryMethod(); 
                      $dm->setAverageDays(1); 
                      $dm->setIsAPickup(true); 
                      $dm->setServiceId(9999); 
                      $dm->setFixedPrice(0); 
                      $dm->setValid(true); 
                      $cp->setCompanyDeliveryMethod($dm); 
                      $em->persist($dm); 
                      $em->persist($cp); 
                      $em->flush(); 
                    } 
                  } 
                  if ($cp->getIsAPickup()){ 
                    $dm = $cp->getCompanyDeliveryMethod(); 
                    if(!empty($cp->getCompanyDeliveryMethod()->getId())){ 
                      $idPickUp = $cp->getCompanyDeliveryMethod()->getId(); 
                      $entityManager = $this->getDoctrine()->getManager(); 
                      $PickUpRetake = $entityManager->getRepository(DeliveryMethod::class)->find($cp->getId()); 
                      $cp->setCompanyDeliveryMethod(null); 
                      $entityManager->persist($cp); 
                      $entityManager->flush(); 
                  }else{ 
                    // if($request->hasPreviousSession('pickupSchedule')) { 
                      $dm->setAverageDays(2); 
                      $dm->setPickupSchedule($request->get('pickupSchedule')); 
                      $address= $cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.pickUpAdress'); 
                      $dm->setPickupAddress($address); 
                    // } 
                  } 
 
                    $withPacking = $request->hasPreviousSession('withPacking') 
                    && $request->get('withPacking') == 'true'; 
 
                    $dm->setWithPacking($withPacking); 
 
                    $em->persist($dm); 
                  } 
                } 
                $newAddress_phone = $request->request->get('pickup_phone'); 
                $newAdresse_name =  $request->request->get('pickup_name'); 
                if($cart->getPickupAddress() != null){ 
                  $UserInformation = $this->getUser(); 
                  if (!empty($newAddress_phone)){ 
                    $UserInformation->setPhone($newAddress_phone); 
                  }else{ 
                    $this->addFlash('error', "Veuillez noter votre numéro de téléphone"); 
                    return $this->redirectToRoute('checkout'); 
                  } 
                    $UserInformation->setFirstname($newAdresse_name); 
                  $em->persist($UserInformation); 
                  $em->flush(); 
                } 
            } 
 
            $cart->resetCalculations(); 
 
            $em->persist($cart); 
            $em->flush(); 
 
            if ($request->get('action_bulkshipping') == "on" && $request->get('pickupScheduleCheckbox') != "cueillette" ) { 
              return $this->redirectToRoute('bulkship'); 
            } 
 
            if($redirect) { 
              return $this->redirectToRoute('cartPayment'); 
            } 
        } 
         
        // We set the coupon if users has a valid one 
         
        $couponMarketing= $this->session->get('coupon_marketing'); 
        $twigData['couponMarketing']=false; 
 
        if($couponMarketing){ 
          $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing); 
          if(!empty($cartCoupon)){ 
            $twigData['couponMaketing']=$cartCoupon; 
          } 
        } 
 
        $userCouponList=[]; 
        $tempCouponLists= $em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId()); 
        // we only get not used coupon by the user 
        foreach ($tempCouponLists as $cartCoupon ) { 
          if($cartCoupon->getOneTimeOnly()){ 
            if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())) 
                continue; 
            else 
              array_push($userCouponList,$cartCoupon); 
          }else 
            array_push($userCouponList,$cartCoupon); 
        } 
 
        $twigData['couponLists'] = $userCouponList; 
         
        return $twigData; 
    } 
 
    /** 
     * @Route({ 
     *          "fr": "/panier", 
     *          "en": "/cart" 
     *      }, name="viewCart") 
     * @Template("frontend/cart.html.twig") 
     */ 
    public function viewCart(UserService $userServ, Request $request){ 
        $twigData = array(); 
        $twigData['loader'] = true; 
        $twigData['suggestedProducts']= $userServ->findProductsToSuggest(); 
 
        $cart = $userServ->getCart(); 
        $cart->setUsedCoupon(null); 
        $cart->setDeliveryChoiceDate(null); 
        $cart->setPreOrder(false); 
        $cart->setNoteFromBuyer(null); 
        $cart->setPreOrderNow(false); 
        $cart->setDateCreated(new \DateTime(), new \DateTimeZone('America/New_York')); 
        $cart->setDatePayment(new \DateTime(), new \DateTimeZone('America/New_York')); 
 
        $em = $this->getDoctrine()->getManager(); 
 
        //To avoid a lot of bug occuring when the user go back and forth from Payment to card we reset the cart 
        $cart->resetCalculations(); 
 
        $cartForm= $this->createForm(CartType::class, $cart); 
        $cartForm->handleRequest($request); 
 
 
        if ($request->get("alert_nodelivery_puro") == "true") { 
          $twigData['alert_nodelivery_puro'] = "true"; 
        } 
 
        if ($request->get("alert_nodelivery_cold") == "true") { 
          $twigData['alert_nodelivery_cold'] = "true"; 
        } 
 
        if ($request->get("alert_nodelivery_alcohol") == "true") { 
          $twigData['alert_nodelivery_alcohol'] = "true"; 
        } 
        $claudia = $em->getRepository(User::class)->findOneBy(["email" => "corpo@maturin.ca"])->getEmail(); 
 
        /* Fix a bug that sometime having product erased they come back */ 
        if($cartForm->get('update')->isClicked()){ 
          if ($this->getUser() && $this->getUser()->getEmail() == $claudia){ 
          }else{ 
 
            $forceRedirect=false; 
            foreach($cart->getProducts() as $p){ 
              if (!$p->getProduct()->getIsBoxOfProducts()){ 
            // getQuantityMaxProd valable que en preOrder pour augmenter les ventes en période de fetes, permet au producteur d'anticiper  
            // et de vendre plusque quantité hebdomadaire 
            //If the quantity we have in stock is lower than the one the customer wants 
            $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                if ($getQtyReadyToShip) { 
                  if ($p->getProduct()->getQuantityMaxProd() > 0){ 
                    $getQtyComing = $p->getProduct()->getQuantityMaxProd(); 
                  }else{ 
                    $getQtyComing = 0; 
                  } 
                $qtyMaximumToSell = $getQtyReadyToShip + $getQtyComing; 
               if($qtyMaximumToSell < $p->getQuantity()) { 
                if($qtyMaximumToSell == 0){ 
                  $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                  $em->remove($p); 
                  $em->flush(); 
                  $forceRedirect=true; 
                  continue; 
                }else{ 
                  $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                  $p->setQuantity($getQtyReadyToShip); 
                  $em->persist($p); 
                  $em->flush(); 
                  $forceRedirect=true; 
                  continue; 
                } 
 
                  } 
                } 
              } 
 
          // If the jit product pass the weekly  qty to sell 
            if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){ 
              $qtyWeeklySoldForProduct = $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId()); 
              if (!$qtyWeeklySoldForProduct) { 
                $qtyWeeklySoldForProduct = 0; 
              } 
              $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
              
              if ($getQtyReadyToShip) { 
                if($qtyWeeklySoldForProduct + $p->getQuantity() > $getQtyReadyToShip ) { 
                  if ($p->getQuantity() <= $qtyWeeklySoldForProduct){ 
                    $p->setQuantity($p->getQuantity()); 
                    $em->persist($p); 
                    $em->flush(); 
                    $forceRedirect=true; 
                    continue; 
                  }else{ 
                    $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                    $p->setQuantity($getQtyReadyToShip); 
                    $em->persist($p); 
                    $em->flush(); 
                    $forceRedirect=true; 
                    continue; 
                  } 
                } 
              } 
            } 
            if ($p->getProduct()->getIsBoxOfProducts()){ 
              $getAllProducts = $p->getProduct()->getProductsInBox(); 
              foreach ($getAllProducts  as $getAllProduct) { 
                $getQuantityforBox = $p->getQuantity() * $getAllProduct->getQuantity(); 
                if ($getQuantityforBox > $p->getProduct()->getQtyReadyToShip()){ 
                  $quantityBoxLeft = intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity())); 
                  if ($quantityBoxLeft < $p->getQuantity()){ 
                    $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                    $p->setQuantity($quantityBoxLeft); 
                    $em->persist($p); 
                    $em->flush(); 
                    $forceRedirect=true; 
                  } 
                } 
              } 
            } 
          } 
          if($forceRedirect) 
          { 
            return $this->redirectToRoute('viewCart'); 
          } 
        } 
            $em->persist($cart); 
            $em->flush(); 
      } 
 
        // //add by default dth reusable box  
        // $reusableBox = $request->request->get("reusableBox"); 
        // if($cartForm->get('submit')->isClicked()){ 
        //   if ($reusableBox == "addBox" && $this->getUser() && !$this->getUser()->getHasReusableBox() && !$cart->containReusableBox() && $cart->containMaturinRoute()){ 
        //     $productBoxReusable = $em->getRepository(Product::class)->findOneBy(['id'=> 6472]); 
        //     $this->addToCart($productBoxReusable, 1, $userServ, $em); 
        //   }         
        // } 
         
        if($cartForm->isSubmitted() && $cartForm->isValid()){ 
                      
          if ($this->getUser() && $this->getUser()->getEmail() == $claudia){ 
          }else{ 
            $forceRedirect=false; 
            
              foreach($cart->getProducts() as $p){ 
                if (!$p->getProduct()->getIsBoxOfProducts()){ 
                // getQuantityMaxProd valable pour augmenter les ventes en période de fetes, permet au producteur d'anticiper ou claudia de commander plus de volume  
              // et de vendre plusque quantité hebdomadaire 
            //If the quantity we have in stock is lower than the one the customer wants 
               $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                if ($getQtyReadyToShip) { 
                    if ($p->getProduct()->getQuantityMaxProd() > 0){ 
                      $getQtyComing = $p->getProduct()->getQuantityMaxProd(); 
                    }else{ 
                      $getQtyComing = 0; 
                    } 
                      $qtyMaximumToSell = $getQtyReadyToShip + $getQtyComing; 
                  if($qtyMaximumToSell < $p->getQuantity()) { 
                    if($qtyMaximumToSell == 0){ 
                      $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                      $em->remove($p); 
                      $em->flush(); 
                      $forceRedirect=true; 
                      continue; 
                    }else{ 
                      $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                      $p->setQuantity($getQtyReadyToShip); 
                      $em->persist($p); 
                      $em->flush(); 
                      $forceRedirect=true; 
                      continue; 
                    } 
                } 
              } 
            } 
           
 
                // If the jit product pass the weekly  qty to sell 
                if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){ 
                  $qtyWeeklySoldForProduct = $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId()); 
                  if (!$qtyWeeklySoldForProduct) { 
                    $qtyWeeklySoldForProduct = 0; 
                  } 
                  $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                  if ($getQtyReadyToShip) { 
                    if($qtyWeeklySoldForProduct + $p->getQuantity() >= $getQtyReadyToShip ) { 
                      if ($p->getQuantity() <= $qtyWeeklySoldForProduct){ 
                        $p->setQuantity($p->getQuantity()); 
                        $em->persist($p); 
                        $em->flush(); 
                        
                        continue; 
                      }else{ 
                        $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                        $p->setQuantity($getQtyReadyToShip); 
                        $em->persist($p); 
                        $em->flush(); 
                        $forceRedirect=true; 
                        continue; 
                      } 
                    } 
                  } 
                } 
 
                if ($p->getProduct()->getIsBoxOfProducts()){ 
                  $getAllProducts = $p->getProduct()->getProductsInBox(); 
                  foreach ($getAllProducts  as $getAllProduct) { 
                    $getQuantityforBox = $p->getQuantity() * $getAllProduct->getQuantity(); 
                    if ($getQuantityforBox > $p->getProduct()->getQtyReadyToShip()){ 
                      $quantityBoxLeft = intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity())); 
                      if ($quantityBoxLeft < $p->getQuantity()){ 
                        $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                        $p->setQuantity($quantityBoxLeft); 
                        $em->persist($p); 
                        $em->flush(); 
                        $forceRedirect=true; 
                      } 
                    } 
                  } 
                } 
              } 
              if($forceRedirect) 
              { 
                return $this->redirectToRoute('viewCart'); 
              } 
 
 
 
          //bloque si commande de produit Naya (bouteille d'eau) + que 10 
          foreach($cart->getProducts() as $p){ 
          if($p->getQuantity() >= 10 && $p->getProduct()->getCompany()->getId() == 525 && $p->getProduct()->isShippedByMaturin() == true){ 
            $this->addFlash('error', 'Désolé vous ne pouvez pas commander plus de 10 produits de la compagnie Naya'); 
            return $this->redirectToRoute('viewCart'); 
          } 
 
          // $requestDate = $request->request->get("livraisonDate"); 
          // $livDate = new \DateTime($requestDate); 
 
          //   $cart->setDeliveryChoiceDate($livDate); 
        } 
            $em->persist($cart); 
            $em->flush(); 
 
 
           
          } 
 
            try { 
                //Erase all cart products with 0 quantity 
                foreach($cart->getProducts() as $p){ 
                    if($p->getQuantity() <= 0){ 
                        $cart->removeProduct($p); 
                        $em->remove($p); 
                    } 
                } 
 
                //If Shipping was selected mean the user is going back and forth 
                //so let's force a recalculate 
                if($cart->getShippingAddress()){ 
                    $cart->calculateFees(); 
                } 
 
                // save cart changes 
                $em->persist($cart); 
                $em->flush(); 
 
                if(!$cartForm->get('update')->isClicked()){ 
                    if($userServ->getUser()){ 
                        if($cartForm->has('recurring')){ 
                            $recurring = $cartForm->get('recurring')->getData(); 
 
                            //User asked to add this to this recurring order 
                            if($recurring){ 
                                $rCart = $recurring->getCart(); 
 
                                foreach($cart->getProducts() as $p){ 
                                    $p->setIsRecurringOneTimeOnly(true); 
                                    $cart->removeProduct($p); 
                                    $rCart->addProduct($p); 
 
                                    $em->persist($p); 
                                } 
                                $em->persist($cart); 
                                $em->persist($rCart); 
                                $em->flush(); 
 
                                $this->addFlash('success', 'Vos produits on été ajouté à cette commande récurrente.'); 
                                return $this->redirectToRoute('recurringOrderEntry', array('id' => $recurring->getId())); 
                            } 
                        } 
 
                        return $this->redirectToRoute('checkout', array('id' => $cart->getId())); 
                    }else 
                        return $this->redirectToRoute('fos_user_security_login'); 
                }else{ 
                    $this->addFlash('success', 'Votre panier a été modifié avec succès.'); 
                    return $this->redirectToRoute('viewCart'); 
                } 
 
            } 
            catch (\Exception $e ){ 
                /* 
                var_dump($e->getMessage()); 
                die(); 
                 // */ 
                $this->addFlash('error', 'Une erreur est survenu, veuillez contacter notre support.'); 
            } 
          
        } 
 
        $twigData['form'] = $cartForm->createView(); 
        $twigData['cart']=$cart; 
        $twigData['hideSideMenu'] = true; 
 
        if ($this->getUser() && $this->getUser()->getEmail() == $claudia){ 
        }else{ 
 
       
           
        //Check if all Maturin product has quantity 
        $forceRedirect=false; 
        foreach($cart->getProducts() as $p){ 
            //If the product was put unavailable since 
            if(!$p->getProduct()->getAvailable() || !$p->getProduct()->isSalable()){ 
                $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                $em->remove($p); 
                $em->flush(); 
                $forceRedirect=true; 
                continue; 
            } 
 
 
 
            if($p->isShippedByMaturin()){ 
                //Check if they are all valid Solex product 
                // if(empty($p->getProduct()->getSolexId()) && !$p->getProduct()->getHasMultipleProducts()){ 
                //     $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                //     $em->remove($p); 
                //     $em->flush(); 
                //     $forceRedirect=true; 
                //     continue; 
                // } 
 
                // //If the quantity we have in stock is lower than the one the customer wants 
                // $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                // if ($getQtyReadyToShip) { 
                //   if($getQtyReadyToShip < $p->getQuantity()) { 
                //     if($getQtyReadyToShip == 0){ 
                //       $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                //       $em->remove($p); 
                //       $em->flush(); 
                //       $forceRedirect=true; 
                //       continue; 
                //     }else{ 
                //       $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                //       $p->setQuantity($getQtyReadyToShip); 
                //       $em->persist($p); 
                //       $em->flush(); 
                //       $forceRedirect=true; 
                //       continue; 
                //     } 
                //   } 
                // } 
                // // If the jit product pass the weekly  qty to sell 
                // if($p->getProduct()->getIsJustInTime()){ 
                //   $qtyWeeklySoldForProduct = $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId()); 
                //   if (!$qtyWeeklySoldForProduct) { 
                //     $qtyWeeklySoldForProduct = 0; 
                //   } 
                //   $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                //   if ($getQtyReadyToShip) { 
                //     if($qtyWeeklySoldForProduct + $p->getQuantity() > $getQtyReadyToShip ) { 
                //       $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                //       $em->remove($p); 
                //       $em->flush(); 
                //       $forceRedirect=true; 
                //       continue; 
                //     } 
                //   } 
                // } 
            }else{ 
                if(empty($p->getValidDeliveryMethods())){ 
                    $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'a aucune livraison disponible"); 
                    $twigData['noGo']= true; 
 
                } 
            } 
        } 
        if($forceRedirect) 
            return $this->redirectToRoute('viewCart'); 
      } 
        //Let's check if the cart is legit 
 
        if($cart->getTotalProductsMaturinDeliveryOnly() < 25 && $cart->getHasMaturinDeliveryProducts()) { 
          $this->addFlash('warning', "Le montant minimal d'achat est de 25$"); 
          $twigData['noGo']=true; 
        } 
         
 
        return $twigData; 
    } 
 
 
 
 
    /** 
     * @Route( 
     *      "/API/cart/add/{id}/{quantity}/{subscribeType}", 
     *      name="addToCart", 
     *      options = { "expose" = true }, 
     *      defaults = { 
     *          "quantity" = 1, 
     *          "subscribeType" = false 
     *      } 
     *  ) 
     */ 
    public function addToCart(Product $product, $quantity, UserService $userServ, EntityManagerInterface $em, $subscribeType=false) 
    { 
        $response = new JsonResponse(); 
        $cart = $userServ->getCart(); 
        //$cart->setUser($userServ->getUser()); 
 
        $cartItem = false; 
        foreach($cart->getProducts() as $key => $p ){ 
            if($p->getProduct()->getId() == $product->getId()){ 
                $cartItem = $cart->getProducts()->get($key); 
                break; 
            } 
        } 
 
        if($cartItem){ 
            $qty = ($cartItem->getQuantity()) + 1; 
            $cartItem->setQuantity($qty); 
            $cart->getProducts()->set($key, $cartItem); 
        }else{ 
            $cartItem = new CartProduct(); 
            $cartItem->setProduct($product); 
            $cartItem->setQuantity($quantity); 
 
            $cart->addProduct($cartItem); 
        } 
 
        if($subscribeType){ 
            $cartItem->setRecurringFrequency($subscribeType); 
        } 
 
        //If browsing a association 
        //And this project is in a association 
        $testAssociation = $userServ->getAssociationUserIsBrowsing(); 
        if($testAssociation && $product->getCompany()->getAssociations()->contains($testAssociation)){ 
            $cartItem->setAddedWhenBeingInAssociation($testAssociation); 
 
            if($testAssociation->getVariableValueByCodeName('orders.canPickUp')){ 
                $dm = new DeliveryMethod(); 
                $dm->setAverageDays(1); 
                $dm->setIsAPickup(true); 
                $dm->setServiceId(9999); 
                $dm->setFixedPrice(0); 
                $dm->setValid(true); 
 
                $testSchedule = $testAssociation->getVariableValueByCodeName('orders.pickUpSchedule'); 
                if($testSchedule) 
                    $dm->setPickupSchedule($testSchedule); 
 
                $testAddress= $testAssociation->getVariableValueByCodeName('orders.pickUpAdress'); 
                if($testAddress) 
                    $dm->setPickupAddress($testAddress); 
 
                $cartItem->setCompanyDeliveryMethod($dm); 
                $em->persist($dm); 
            } 
        } 
 
        $em->persist($cartItem); 
        $em->persist($cart); 
        $em->flush(); 
 
        $response->setData(array( 
            'success' => true, 
            'totalCart' => number_format($cart->getSubTotalToPay(false, false),2).'$' 
        )); 
 
        return $response; 
    } 
 
 
    /** 
     * @Route({ 
     *      "fr": "/livraison/ville/ajax_search/{province}", 
     *      "en": "/delivery/city/ajax_search" 
     *      }, 
     *      name="cityAdressAJAXSearch" 
     * ) 
     * 
     */ 
    public function cityAdressAJAXSearch(UserService $userServ, Request $request, EntityManagerInterface $em,$province) { 
      $search_query = $request->get("term"); 
      if (empty($search_query)) { 
        die(json_encode(["results"=>[]])); 
      } 
      $stringCut = explode('-', $search_query); 
 
      if (count($stringCut) > 1){ 
        $search_query = "%".str_replace(" ", "%", trim($stringCut[1]))."%"; 
       }else{ 
        $search_query = "%".str_replace(" ", "%", trim($search_query))."%"; 
       } 
     
      $search_results = $em->getRepository(City::class)->searchByName($search_query); 
      // $search_results = $em->getRepository(City::class)->searchByNameAndProvince($search_query,$province); 
 
      $results = []; 
      foreach($search_results as $result) { 
        $results[] = ["id"=>$result->getId(), "text"=>$result->getName()]; 
      } 
      die(json_encode(["results"=>$results])); 
    } 
 
 
    public function CouponTuango($coupon) { 
      $user = $this->getUser(); 
      $couponTuango = false; 
      $fileTuango = $this->getParameter('GiftCouponTuango'); 
      $file = fopen($fileTuango, "rw"); 
      while (!feof($file) ) { 
        $lines[] = fgetcsv($file, 1500, " "); 
      } 
      
      foreach ($lines as $line => $val) { 
        // dump($val); 
        $searchValue = in_array($coupon, $val); 
          if($searchValue == true){ 
            $couponTuango = true; 
          } 
        } 
       
      fclose($file); 
      $em = $this->getDoctrine()->getManager(); 
      $cartCoupon = $em->getRepository(CartCoupon::class)->findBy(["code" => $coupon]); 
       
      
        // dump($cartCoupon); 
      if ($couponTuango == true && empty($cartCoupon)){ 
        // dump('entrer'); 
      $AddCoupon = new CartCoupon(); 
      $AddCoupon->setOneTimeOnly(1); 
      $AddCoupon->setType(2); 
      $AddCoupon->setAmount(80); 
      $AddCoupon->setCode($coupon); 
      $AddCoupon->setDateFrom(new \DateTime()); 
      $AddCoupon->setDateTo(new \DateTime("+1 month")); 
      $AddCoupon->setForUser($this->getUser()); 
      $em->persist($AddCoupon); 
      $em->flush(); 
 
      return true; 
       
    }else{ 
      return false; 
    } 
       
       
    } 
 
 
    public function CouponCabaneMaturin($coupon) { 
      $user = $this->getUser(); 
      $cart = $user->getCart(); 
      // $cart->getProducts(); 
      $couponOption1 = false; 
      $couponOption2 = false; 
      $couponOption3 = false; 
 
      $option1 = $this->getParameter('GiftCabaneOption1'); 
      $option2 = $this->getParameter('GiftCabaneOption2'); 
      $option3 = $this->getParameter('GiftCabaneOption3'); 
 
 
      $fileOption1 = fopen($option1, "rw"); 
      $fileOption2 = fopen($option2, "rw"); 
      $fileOption3 = fopen($option3, "rw"); 
 
      //send all of them in array 
      while (!feof($fileOption1) ) { 
        $linesOption1[] = fgetcsv($fileOption1, 150, " "); 
      } 
      while (!feof($fileOption2) ) { 
        $linesOption2[] = fgetcsv($fileOption2, 150, " "); 
      } 
      while (!feof($fileOption3) ) { 
        $linesOption3[] = fgetcsv($fileOption3, 150, " "); 
      } 
 
 
     // check in array option1 
      foreach ($linesOption1 as $lineOption1 => $val) { 
        $searchValue = in_array($coupon, $val); 
          if($searchValue == true){ 
            $couponOption1 = true; 
          } 
      } 
      // check in array option2 
      foreach ($linesOption2 as $lineOption2 => $val) { 
        // dump($val); 
        $searchValue = in_array($coupon, $val); 
          if($searchValue == true){ 
            $couponOption2 = true; 
          } 
      } 
      // check in array option3 
      foreach ($linesOption3 as $lineOption3 => $val) { 
        // dump($val); 
        $searchValue = in_array($coupon, $val); 
          if($searchValue == true){ 
            $couponOption3 = true; 
          } 
      } 
 
      // close files  
      fclose($fileOption1); 
      fclose($fileOption2); 
      fclose($fileOption3); 
 
      //search if coupon already exist  
      $em = $this->getDoctrine()->getManager(); 
      $cartCoupon = $em->getRepository(CartCoupon::class)->findBy(["code" => $coupon]); 
      //if not exist add it in BD  
 
      $applyOption=0; 
      // check if product cabane a sucres is in cart 
      foreach ($cart->getProducts() as $ProductIncart){ 
        if ($ProductIncart->getProduct()->getId() == 9287){ 
          $applyOption = $ProductIncart->getProduct()->getId(); 
        }elseif ($ProductIncart->getProduct()->getId() == 9288) { 
          $applyOption = $ProductIncart->getProduct()->getId(); 
        }elseif ($ProductIncart->getProduct()->getId() == 9289) { 
          $applyOption = $ProductIncart->getProduct()->getId(); 
        } 
      } 
 
  
    if (empty($cartCoupon)){ 
        //first otpion 75$ == cabane 2-4pers (100$) free 
        if ($couponOption1 == true && $applyOption == 9287){ 
           
        $AddCoupon = new CartCoupon(); 
        $AddCoupon->setOneTimeOnly(1); 
        $AddCoupon->setType(2); 
        $AddCoupon->setAmount(100); 
        $AddCoupon->setCode($coupon); 
        $AddCoupon->setDateFrom(new \DateTime()); 
        $AddCoupon->setDateTo(new \DateTime("+1 month")); 
        $AddCoupon->setForUser($this->getUser()); 
        $em->persist($AddCoupon); 
        $em->flush(); 
        
        return true; 
         
        //first otpion 110$ == cabane 4-6pers (155$) free 
      }elseif ($couponOption2 == true && $applyOption == 9288){ 
     
        $AddCoupon = new CartCoupon(); 
        $AddCoupon->setOneTimeOnly(1); 
        $AddCoupon->setType(2); 
        $AddCoupon->setAmount(155); 
        $AddCoupon->setCode($coupon); 
        $AddCoupon->setDateFrom(new \DateTime()); 
        $AddCoupon->setDateTo(new \DateTime("+1 month")); 
        $AddCoupon->setForUser($this->getUser()); 
        $em->persist($AddCoupon); 
        $em->flush(); 
 
        return true; 
        //first otpion 110$ == cabane 4-6pers (225$) free 
      }elseif ($couponOption3 == true && $applyOption == 9289){ 
           
        $AddCoupon = new CartCoupon(); 
        $AddCoupon->setOneTimeOnly(1); 
        $AddCoupon->setType(2); 
        $AddCoupon->setAmount(225); 
        $AddCoupon->setCode($coupon); 
        $AddCoupon->setDateFrom(new \DateTime()); 
        $AddCoupon->setDateTo(new \DateTime("+1 month")); 
        $AddCoupon->setForUser($this->getUser()); 
        $em->persist($AddCoupon); 
        $em->flush(); 
 
        return true; 
         
      }else { 
        return false; 
      } 
  } 
  return false; 
    } 
 
 /** 
     * @Route({ 
     *          "fr": "/subscriptionVersproduit/{id}", 
     *          "en": "/subscriptionToProduct/{id}", 
     *      }, 
     *      name="subscriptionToProduct") 
     * 
     */ 
    public function addSubscriptionslikeproduct(Request $request, UserService $userServ, $id){ 
    $em = $this->getDoctrine()->getManager(); 
 
    $productId = $request->request->get('productId'); 
    $subscriptionId = $request->request->get('subscriptionId');; 
   
    $subscriptions = $em->getRepository(Subscription::class)->findBy(["id"=>$subscriptionId]); 
    $cart = $userServ->getCart(); 
 
    foreach ($subscriptions as $subscription) { 
      $quantity = $subscription->getQuantity(); 
      $getSubscritpionProducts = $em->getRepository(Product::class)->findBy(["id"=>$productId]); 
      foreach ($getSubscritpionProducts as $getSubscritpionProduct) { 
        $this->addToCart($getSubscritpionProduct, $quantity, $userServ, $em); 
      } 
  //Let's see if we join it with a subscription 
  if ($subscription) { 
    $cart->setSendWithSubscription($subscription); 
    $found = false; 
    foreach($cart->getProducts() as $cp){ 
    if($cp->getProduct() == $getSubscritpionProduct){ 
      $found = true; 
            $cp->setOverwriteSubscription(true); 
           } 
      } 
             if(!$found){ 
               //Check if product in the cart 
               $cp = new CartProduct(); 
               $cp->setQuantity($quantity); 
               $cp->setProduct($getSubscritpionProduct); 
               $cp->setOverwriteSubscription(true); 
               $cart->addProduct($cp); 
               $em->persist($cart); 
               $em->persist($cp); 
              $em->flush(); 
            } 
   } 
    } 
 
    $this->addFlash('success', 'Ce produit a été ajouté a votre panier'); 
    return $this->redirectToRoute('viewCart');  
   } 
 
 
 
 
 /** 
     * @Route({ 
     *          "fr": "/SauvegardeNouvelleAddresse/", 
     *          "en": "/SaveNewAdress/", 
     *      }, 
     *      name="SaveNewAdress") 
     * 
     */ 
    public function SaveNewAdress(Request $request, UserService $userServ){ 
    $em = $this->getDoctrine()->getManager(); 
    $cart = $userServ->getCart(); 
    if ($request->request->get('adresse_autocomplete')){ 
      $newadresseAutocomplete = $request->request->get('adresse_autocomplete'); 
    }else{ 
      $newadresseAutocomplete = $request->request->get('adresse_manuel'); 
    } 
   
    $pattern = '/\d+/'; 
    preg_match($pattern, $newadresseAutocomplete, $civicnumber); 
 
     
    $pattern = strlen($civicnumber[0]); 
    $streetname = substr($newadresseAutocomplete, $pattern); 
 
    $arrayAutocomplete = explode(', ', trim($streetname)); 
     
        $newAddress_civicnumber = $civicnumber[0]; 
        $newAddress_streetname = $arrayAutocomplete[0]; 
        $newAddress_phone = $request->request->get('adresse_phone'); 
        $newAddress_province = $request->request->get('adresse_province'); 
        $newAddress_zipcode =  $request->request->get('adresse_zipcode'); 
        $adresse_unit = $request->request->get('adresse_unit'); 
        $newAddress_city = $request->request->get('adresse_city'); 
        $newAdresse_name =  $request->request->get('adresse_name'); 
 
        $findTheCity = $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]); 
       
        if ($findTheCity == null){ 
          $findTheCity = new City(); 
 
          $findTheCity->setName(trim($newAddress_city)); 
          $findTheCity->setMrc(trim($newAddress_city)); 
          $findTheCity->setProvince(trim($newAddress_province)); 
 
          $findTheRegion = $em->getRepository(Region::class)->findBy(["name"=>'defaut']); 
          $findTheCity->setRegion($findTheRegion[0]); 
 
          $em->persist($findTheCity); 
          $em->flush(); 
 
          $charlie = $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail(); 
          $userServ->sendEmail('Une nouvelle ville a été ajouté', '<p>La ville ,' . $newAddress_city . ' a été ajouté dans la base de données</p>', false, $charlie); 
        } 
        $user = $userServ->getUser(); 
 
        $UserShippingLocation = new UserShippingLocation(); 
       
        $UserShippingLocation->setName($newAdresse_name); 
          // ajout de condition format et correspond au type de data attendu  
        $UserShippingLocation->setPhone($newAddress_phone); 
        $UserShippingLocation->setCivicNumber($newAddress_civicnumber); 
        $UserShippingLocation->setStreetName($newAddress_streetname); 
        $UserShippingLocation->setUnit($adresse_unit); 
        $UserShippingLocation->setCity($newAddress_city); 
        $UserShippingLocation->setZipCode($newAddress_zipcode); 
        $UserShippingLocation->setProvince($newAddress_province); 
        $UserShippingLocation->setUser($user); 
        $UserShippingLocation->setEmail($this->getUser()->getEmail()); 
         
        $em->persist($UserShippingLocation); 
        $cart->setShippingAddress($UserShippingLocation); 
        $em->persist($cart); 
        $em->flush(); 
 
    $this->addFlash('success', 'Votre adresse a été ajouté avec succes'); 
    return $this->redirectToRoute('checkout');  
   } 
 
   /** 
     * @Route({ 
     *          "fr": "/PaymentChoice/maturinRecolte", 
     *          "en": "/PaymentChoice/maturinRecolte", 
     *      }, 
     *      name="PaymentChoice") 
     * 
     * @Security("has_role('ROLE_ADMIN')") 
     * @Template("/frontend/newPayment.html.twig") 
     */ 
    public function PaymentChoice(Request $request, UserService $userServ, PaymentService $paymentServ, DistributorService $distributorServ,  TwigGlobalVariables $twigGlobalVariablesService){ 
      $em = $this->getDoctrine()->getManager(); 
      $user = $userServ->getuser(); 
      $cart = $user->getCart(); 
      $twigData =[]; 
      $twigData['cards']= null; 
      if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){ 
        // if(!$cart->hasMaturinShipping()){ 
          if($cart->hasMaturinShipping()){ 
          $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart); 
        } 
 
        //Update the Shipping cost 
        if(!empty($twigData['shippingMaturin'])){ 
          $maturinShipping = current($twigData['shippingMaturin']); 
        } else { 
          $maturinShipping = false; 
        } 
        
 
        $found = false; 
 
        if($maturinShipping){ 
            foreach($twigData['shippingMaturin'] as $s){ 
                if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){ 
                    $found = true; 
 
                    $cart->setShippingMaturinCost($s->estimatedCost); 
                    $cart->setShippingMaturinCarrierName($s->carrierName); 
                    $cart->setShippingMaturinServiceName($s->serviceName); 
                    $cart->setShippingMaturinServiceId($s->serviceId); 
 
                    $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart); 
                   //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate)); 
                    $cart->setShippingMaturinEstimatedDate($estimatedCartDate); 
                    $twigData['currentShipping'] = $s; 
                    break; 
                } 
              } 
 
              if(!($request->request->has('maturinShipping') && $found)){ 
 
                  $cart->setShippingMaturinCost($maturinShipping->estimatedCost); 
                  $cart->setShippingMaturinCarrierName($maturinShipping->carrierName); 
                  $cart->setShippingMaturinServiceName($maturinShipping->serviceName); 
                  $cart->setShippingMaturinServiceId($maturinShipping->serviceId); 
 
                  //// old estimate not working anymore for delivery date we change it to new estimation route 
                  $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart); 
                  $maturinShipping->estimatedDate = $estimatedCartDate["date"]; 
                  $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate); 
                 
                  //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate)); 
 
                  $twigData['currentShipping'] = $maturinShipping; 
              } 
              $em->persist($cart); 
              $em->flush(); 
            }else{ 
                if($cart->hasMaturinShipping()){ 
                    //Should be an error with the shipping 
                    //In theory the flash should show the error to user 
                    //so we redirect to shipping address 
                    $twigData['noGo'] = true; 
                    return $this->redirectToRoute('checkout'); 
                } 
            } 
        } 
 
        $shippingAddress = $cart->getShippingAddress(); 
        //We need a shipping address for the taxes 
        if($shippingAddress) { 
            $cart->calculateFees(); 
            $em->persist($cart); 
            $em->flush(); 
        } 
        $PuroTest = null; 
        if ($shippingAddress){ 
          $getMethodLivraisons = $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]); 
          foreach ($getMethodLivraisons as $getMethodLivraison) { 
            if ($getMethodLivraison->getType() == 'maturin') 
            $PuroTest = 'maturin'; 
          } 
        } 
        $twigData['puroConfirm'] = $PuroTest; 
 
       
      $twigData['hideSideMenu'] = true; 
      if ($user->getStripeAccountId()){ 
        $acct = \Stripe\Customer::retrieve($user->getStripeAccountId()); 
        for ($i=0; $i < count($acct->sources->data) ; $i++) {  
          if ($acct->default_source == $acct->sources->data[$i]->id){ 
            $default_source = true; 
          }else{ 
            $default_source = false; 
          } 
          $twigData['cards'][] = array ( 
                  'card_id' => $acct->sources->data[$i]->id, 
                  'default_source' => $default_source, 
                  'last4' => $acct->sources->data[$i]->last4, 
                  'exp_month' => $acct->sources->data[$i]->exp_month, 
                  'exp_year' => $acct->sources->data[$i]->exp_year); 
        } 
      } 
       
      if ($this->getUser() && $this->getUser()->getIsBetaTester()){ 
        if($request->isMethod('post') && empty($request->request->get('validePayment'))){ 
          //  dump('ok12'); 
          // dd($request); 
            if(!empty($request->request->get('stripeToken'))){ 
              $cart->setStripeToken($request->request->get('stripeToken')); 
            } 
            //First time paying, let's create him a account 
            if(empty($user->getStripeAccountId())){ 
              if (empty($cart->getStripeToken())) 
                  throw new \Exception("The Token was not generated correctly"); 
 
              $customer = \Stripe\Customer::create([ 
                  'source' => $cart->getStripeToken(), 
                  'email' => $user->getEmail(), 
              ]); 
 
              $user->setPaymentLast4digits(current($customer->sources->data)->last4); 
              $user->setStripeAccountId($customer->id); 
 
              $em->persist($user); 
            }elseif(!empty($cart->getStripeToken()) || !empty($request->request->get('stripeToken'))){ 
           
              $acct->sources->create(array("source" => $request->request->get('stripeToken'))); 
              
              $user->setPaymentLast4digits(current($customer->sources->data)->last4); 
            } 
            $em->persist($user); 
 
          $em->flush(); 
           
          return $this->redirectToRoute('PaymentChoice'); 
        }elseif($request->isMethod('post') && $request->request->get('validePayment') == "Soumettre") { 
          $default_source = null; 
          $default_source = $request->request->get('default_source'); 
          //It appear we need to update it 
          if($default_source != null){ 
            // Set the new card as the customers default card 
            $acct->default_source = $twigData['cards'][$default_source]['card_id']; 
            $acct->save(); 
          }else{ 
            $this->addFlash('error', 'Il faut enregistrer une carte'); 
            return $this->redirectToRoute('PaymentChoice'); 
          } 
          //Lets start with the coupon see if it's valid 
        $coupon = $request->get("coupon"); 
        if(!empty($coupon) ){ 
          $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
          $couponSearchTuango = false; 
          $couponSearchTuango =  $this->CouponTuango($coupon); 
          $couponCabane = false; 
          $couponCabane =  $this->CouponCabaneMaturin($coupon); 
 
          if ($couponSearchTuango != false || $couponCabane != false){ 
            $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
          } 
            if(empty($cartCoupon)){ 
              if ($couponSearchTuango == false && $couponCabane == false){ 
                $this->addFlash('error', "Merci de vérifier votre code coupon ou associez-le au bon produit"); 
                return $this->redirectToRoute('checkout'); 
              } 
            }else{ 
                //If coupon is a onetimeonly and was already used 
                if($cartCoupon->getOneTimeOnly()){ 
                    if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){ 
                        $this->addFlash('error', "Vous avez déja utilisé ce coupon"); 
                        return $this->redirectToRoute('checkout'); 
                    } 
                } 
                //Check if any money left 
                if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= 0 ){ 
                    $this->addFlash('error', "Ce coupon a un solde restant de 0$"); 
                    return $this->redirectToRoute('checkout'); 
                } 
                $cart->setUsedCoupon($cartCoupon); 
                //$user = $userServ->getUser(); 
                //$user->addCouponUsed($cartCoupon); 
                //$em->persist($user); 
            } 
        }else{ 
          //$user->removeCouponUsed($cartCoupon); 
          $cart->setUsedCoupon(null); 
        } 
        $em->persist($cart); 
        $em->flush(); 
 
          return $this->redirectToRoute('RecapPayment'); 
        } 
 
      }else{ 
        return $this->redirectToRoute('viewCart'); 
    } 
    // We set the coupon if users has a valid one 
         
    $couponMarketing= $this->session->get('coupon_marketing'); 
    $twigData['couponMarketing']=false; 
 
    if($couponMarketing){ 
      $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing); 
      if(!empty($cartCoupon)){ 
        $twigData['couponMaketing']=$cartCoupon; 
      } 
    } 
 
    $userCouponList=[]; 
    $tempCouponLists= $em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId()); 
    // we only get not used coupon by the user 
    foreach ($tempCouponLists as $cartCoupon ) { 
      if($cartCoupon->getOneTimeOnly()){ 
        if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())) 
            continue; 
        else 
          array_push($userCouponList,$cartCoupon); 
      }else 
        array_push($userCouponList,$cartCoupon); 
    } 
 
    $twigData['couponLists'] = $userCouponList; 
      return $twigData; 
  } 
 
 
 /** 
     * @Route({ 
     *          "fr": "/nouveauPanier/maturinRecolte", 
     *          "en": "/NewCart/maturinRecolte" 
     *      }, name="NewViewCart") 
     * @Template("frontend/RecolteCart.html.twig") 
     */ 
    public function NewViewCart(UserService $userServ, Request $request, TwigGlobalVariables $twigGlobalVariablesService){ 
      $twigData = array(); 
      $em = $this->getDoctrine()->getManager(); 
      $twigData['loader'] = true; 
      $twigData['suggestedProducts']= $userServ->findProductsToSuggest(); 
      if ($this->getUser() && $this->getUser()->getIsBetaTester()){ 
      $user= $userServ->getuser(); 
      $userPaidOrders=false; 
      if($user){ 
        $userPaidOrders = $user->getAllCartsProducts(); 
      } 
        $cart = $userServ->getCart(); 
        $cart->setUsedCoupon(null); 
        $cart->setDeliveryChoiceDate(null); 
        $cart->setPreOrder(false); 
        $cart->setNoteFromBuyer(null); 
        $cart->setPreOrderNow(false); 
        $cart->setDateCreated(new \DateTime(), new \DateTimeZone('America/New_York')); 
        $cart->setDatePayment(new \DateTime(), new \DateTimeZone('America/New_York')); 
        
        $forceRedirect=false; 
        $route=[]; 
            foreach($cart->getProducts() as $p){ 
                if (!empty($route)){ 
                  if ($twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') != $route['estimationDelivery']->format('Y-m-d') ){ 
                      $route[] = array( 
                        'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') 
                    ); 
                  } 
                }else{ 
                  $route = array( 
                    'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date'] 
               ); 
               }  
            } 
            sort($route); 
            $twigData['estimationDeliveryDate'] = $route;     
             
        //To avoid a lot of bug occuring when the user go back and forth from Payment to card we reset the cart 
        $cart->resetCalculations(); 
      $twigData['userPaidOrders']= $userPaidOrders; 
 
      $cartForm= $this->createForm(CartType::class, $cart); 
      $cartForm->handleRequest($request); 
 
      if ($request->get("alert_nodelivery_puro") == "true") { 
        $twigData['alert_nodelivery_puro'] = "true"; 
      } 
 
      if ($request->get("alert_nodelivery_cold") == "true") { 
        $twigData['alert_nodelivery_cold'] = "true"; 
      } 
 
      if ($request->get("alert_nodelivery_alcohol") == "true") { 
        $twigData['alert_nodelivery_alcohol'] = "true"; 
      } 
      
      $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; 
 
      // //add by default dth reusable box  
      // $reusableBox = $request->request->get("reusableBox"); 
      // if($cartForm->get('submit')->isClicked()){ 
      //   if ($reusableBox == "addBox" && $this->getUser() && !$this->getUser()->getHasReusableBox() && !$cart->containReusableBox() && $cart->containMaturinRoute()){ 
      //     $productBoxReusable = $em->getRepository(Product::class)->findOneBy(['id'=> 6472]); 
      //     $this->addToCart($productBoxReusable, 1, $userServ, $em); 
      //   }         
      // } 
       
        //bloque si commande de produit Naya (bouteille d'eau) + que 10 
        foreach($cart->getProducts() as $p){ 
          if($p->getQuantity() >= 10 && $p->getProduct()->getCompany()->getId() == 525 && $p->getProduct()->isShippedByMaturin() == true){ 
            $this->addFlash('error', 'Désolé vous ne pouvez pas commander plus de 10 produits de la compagnie Naya'); 
            return $this->redirectToRoute('viewCart'); 
          } 
        }  
         
          if($request->isMethod('post') && $request->request->get('cart_submit') == 'cart_submit'){ 
            foreach($cart->getProducts() as $p){ 
              if (!$p->getProduct()->getIsBoxOfProducts()){ 
                // getQuantityMaxProd valable pour augmenter les ventes en période de fetes, permet au producteur d'anticiper ou claudia de commander plus de volume  
              // et de vendre plusque quantité hebdomadaire 
            //If the quantity we have in stock is lower than the one the customer wants 
              $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
                if ($getQtyReadyToShip) { 
                    if ($p->getProduct()->getQuantityMaxProd() > 0){ 
                      $getQtyComing = $p->getProduct()->getQuantityMaxProd(); 
                    }else{ 
                      $getQtyComing = 0; 
                    } 
                      $qtyMaximumToSell = $getQtyReadyToShip + $getQtyComing; 
                  if($qtyMaximumToSell < $p->getQuantity()) { 
                    if($qtyMaximumToSell == 0){ 
                      $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier"); 
                      $em->remove($p); 
                      $em->flush(); 
                      $forceRedirect=true; 
                      continue; 
                    }else{ 
                      $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                      $p->setQuantity($getQtyReadyToShip); 
                      $em->persist($p); 
                      $em->flush(); 
                      $forceRedirect=true; 
                      continue; 
                    } 
                } 
              } 
            } 
           
 
            // If the jit product pass the weekly  qty to sell 
            if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){ 
              $qtyWeeklySoldForProduct = $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId()); 
              if (!$qtyWeeklySoldForProduct) { 
                $qtyWeeklySoldForProduct = 0; 
              } 
              $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip(); 
              if ($getQtyReadyToShip) { 
                if($qtyWeeklySoldForProduct + $p->getQuantity() >= $getQtyReadyToShip ) { 
                  if ($p->getQuantity() <= $qtyWeeklySoldForProduct){ 
                    $p->setQuantity($p->getQuantity()); 
                    $em->persist($p); 
                    $em->flush(); 
                    
                    continue; 
                  }else{ 
                    $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                    $p->setQuantity($getQtyReadyToShip); 
                    $em->persist($p); 
                    $em->flush(); 
                    $forceRedirect=true; 
                    continue; 
                  } 
                } 
              } 
            } 
 
            if ($p->getProduct()->getIsBoxOfProducts()){ 
              $getAllProducts = $p->getProduct()->getProductsInBox(); 
              foreach ($getAllProducts  as $getAllProduct) { 
                $getQuantityforBox = $p->getQuantity() * $getAllProduct->getQuantity(); 
                if ($getQuantityforBox > $p->getProduct()->getQtyReadyToShip()){ 
                  $quantityBoxLeft = intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity())); 
                  if ($quantityBoxLeft < $p->getQuantity()){ 
                    $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire"); 
                    $p->setQuantity($quantityBoxLeft); 
                    $em->persist($p); 
                    $em->flush(); 
                    $forceRedirect=true; 
                  } 
                } 
              } 
            } 
          } 
      if($forceRedirect) 
      { 
        return $this->redirectToRoute('NewViewCart'); 
      } 
       
            $p->setQuantity($p->getQuantity()); 
            $em->persist($p); 
            $em->flush(); 
            return $this->redirectToRoute('adresse'); 
          } 
 
      $twigData['form'] = $cartForm->createView(); 
      $twigData['cart']= $cart; 
      $twigData['hideSideMenu'] = true; 
 
      //Let's check if the cart is legit 
 
      if($cart->getTotalProductsMaturinDeliveryOnly() < 25 && $cart->getHasMaturinDeliveryProducts()) { 
        $this->addFlash('warning', "Le montant minimal d'achat est de 25$"); 
        $twigData['noGo']=true; 
      } 
    }else{ 
      return $this->redirectToRoute('viewCart'); 
  } 
      return $twigData; 
  } 
 
   /** 
     * @Route({ 
     *          "fr": "/adresse/maturinRecolte", 
     *          "en": "/adresse/maturinRecolte" 
     *      }, name="adresse") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/newAdresse.html.twig") 
     */ 
    public function adresse(UserService $userServ, Request $request,TwigGlobalVariables $twigGlobalVariables, DistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){ 
       
      $twigData = array(); 
        $twigData['hideSideMenu'] = true; 
        $twigData['loader']= true; 
        $cart = $userServ->getCart(); 
        $em = $this->getDoctrine()->getManager(); 
        if ($this->getUser() && $this->getUser()->getIsBetaTester()){ 
        $redirect = true; 
        $route_is_puro_nocold = false; 
        $maturin_type_route_found = false; 
        $shippingAddress = $cart->getShippingAddress(); 
 
        // if(!$cart->hasMaturinShipping()){ 
          // if($cart->hasMaturinShipping()){ 
          //   $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart); 
          // } 
 
          //Update the Shipping cost 
          if(!empty($twigData['shippingMaturin'])){ 
            $maturinShipping = current($twigData['shippingMaturin']); 
          } else { 
            $maturinShipping = false; 
          } 
         
          $found = false; 
 
          if($maturinShipping){ 
              foreach($twigData['shippingMaturin'] as $s){ 
                  if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){ 
                      $found = true; 
 
                      $cart->setShippingMaturinCost($s->estimatedCost); 
                      $cart->setShippingMaturinCarrierName($s->carrierName); 
                      $cart->setShippingMaturinServiceName($s->serviceName); 
                      $cart->setShippingMaturinServiceId($s->serviceId); 
 
                      $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart); 
                     //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate)); 
                      $cart->setShippingMaturinEstimatedDate($estimatedCartDate); 
                    
                      $twigData['currentShipping'] = $s; 
                      break; 
                  } 
              } 
 
              if(!($request->request->has('maturinShipping') && $found)){ 
 
                  $cart->setShippingMaturinCost($maturinShipping->estimatedCost); 
                  $cart->setShippingMaturinCarrierName($maturinShipping->carrierName); 
                  $cart->setShippingMaturinServiceName($maturinShipping->serviceName); 
                  $cart->setShippingMaturinServiceId($maturinShipping->serviceId); 
 
             
                  //// old estimate not working anymore for delivery date we change it to new estimation route 
                  $estimatedCartDate = $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart); 
                  $maturinShipping->estimatedDate = $estimatedCartDate["date"]; 
                  $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate); 
                  //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate)); 
 
                  $twigData['currentShipping'] = $maturinShipping; 
              } 
              $em->persist($cart); 
              $em->flush(); 
            } 
        
        if ($request->get('action') == 'proceed_to_payment') { 
          if ($request->request->get('action_shipping') == 'domicile'){ 
              if ($request->request->get("checkoutAddressSelection") != 'none'){ 
                $shippingAddressId = $request->get("checkoutAddressSelection"); 
                $addr = $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]); 
                $cart->setShippingAddress($addr); 
                $em->persist($cart); 
                $em->flush(); 
              }else{ 
                  $newadresseAutocomplete = $request->request->get('newAddress_autocomplete'); 
                if (!empty($newadresseAutocomplete)){ 
                  
                $pattern = '/\d+/'; 
                preg_match($pattern, $newadresseAutocomplete, $civicnumber); 
             
                $pattern = strlen($civicnumber[0]); 
                $streetname = substr($newadresseAutocomplete, $pattern); 
             
                $arrayAutocomplete = explode(', ', trim($streetname)); 
               
                  $newAddress_civicnumber = $civicnumber[0]; 
                  $newAddress_streetname = $arrayAutocomplete[0]; 
                  $newAddress_phone = $request->request->get('newAddress_phone'); 
                  $newAddress_province = $request->request->get('adresse_province'); 
                  $newAddress_zipcode =  $request->request->get('newAddress_zipcode'); 
                  $adresse_unit = $request->request->get('newAddress_unit'); 
                  $newAddress_city = $request->request->get('adresse_city'); 
                  $newAdresse_name =  $request->request->get('newAddress_name'); 
           
                  $findTheCity = $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]); 
                 
                  if ($findTheCity == null){ 
                    $findTheCity = new City(); 
           
                    $findTheCity->setName(trim($newAddress_city)); 
                    $findTheCity->setMrc(trim($newAddress_city)); 
                    $findTheCity->setProvince(trim($newAddress_province)); 
           
                    $findTheRegion = $em->getRepository(Region::class)->findBy(["name"=>'defaut']); 
                    $findTheCity->setRegion($findTheRegion[0]); 
           
                    $em->persist($findTheCity); 
                    $em->flush(); 
           
                    $charlie = $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail(); 
                    $userServ->sendEmail('Une nouvelle ville a été ajouté', '<p>La ville ,' . $newAddress_city . ' a été ajouté dans la base de données</p>', false, $charlie); 
                  } 
                  $user = $userServ->getUser(); 
           
                  $UserShippingLocation = new UserShippingLocation(); 
                 
                  $UserShippingLocation->setName($newAdresse_name); 
                    // ajout de condition format et correspond au type de data attendu  
                  $UserShippingLocation->setPhone($newAddress_phone); 
                  $UserShippingLocation->setCivicNumber($newAddress_civicnumber); 
                  $UserShippingLocation->setStreetName($newAddress_streetname); 
                  $UserShippingLocation->setUnit($adresse_unit); 
                  $UserShippingLocation->setCity($newAddress_city); 
                  $UserShippingLocation->setZipCode($newAddress_zipcode); 
                  $UserShippingLocation->setProvince($newAddress_province); 
                  $UserShippingLocation->setUser($user); 
                  $UserShippingLocation->setEmail($this->getUser()->getEmail()); 
                   
                  $em->persist($UserShippingLocation); 
                  $cart->setShippingAddress($UserShippingLocation); 
                  $em->persist($cart); 
                  $em->flush(); 
                  $this->addFlash('success', 'Votre adresse a été ajouté avec succes'); 
                }else{ 
                  $this->addFlash('error','Veillez a remplir tous les champs adresse'); 
                  return $this->redirectToRoute('adresse'); 
                } 
                } 
                 
                foreach($cart->getProducts() as $cp) { 
                  $dm = $cp->getCompanyDeliveryMethod(); 
                  if($cp->getAddedWhenBeingInAssociation()){ 
                    if($cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.canPickUp')){ 
                      $dm = new DeliveryMethod(); 
                      $dm->setAverageDays(1); 
                      $dm->setIsAPickup(true); 
                      $dm->setServiceId(9999); 
                      $dm->setFixedPrice(0); 
                      $dm->setValid(true); 
                      $cp->setCompanyDeliveryMethod($dm); 
                      $em->persist($dm); 
                      $em->persist($cp); 
                      $em->flush(); 
                    } 
                  } 
                  if ($cp->getIsAPickup()){ 
                    $dm = $cp->getCompanyDeliveryMethod(); 
                    if(!empty($cp->getCompanyDeliveryMethod()->getId())){ 
                      $idPickUp = $cp->getCompanyDeliveryMethod()->getId(); 
                      $entityManager = $this->getDoctrine()->getManager(); 
                      $PickUpRetake = $entityManager->getRepository(DeliveryMethod::class)->find($cp->getId()); 
                      $cp->setCompanyDeliveryMethod(null); 
                      $entityManager->persist($cp); 
                      $entityManager->flush(); 
                  }else{ 
                    // if($request->hasPreviousSession('pickupSchedule')) { 
                      $dm->setAverageDays(2); 
                      $dm->setPickupSchedule($request->get('pickupSchedule')); 
                      $address= $cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.pickUpAdress'); 
                      $dm->setPickupAddress($address); 
                    // } 
                  } 
                 
                    $withPacking = $request->hasPreviousSession('withPacking') 
                    && $request->get('withPacking') == 'true'; 
 
                    $dm->setWithPacking($withPacking); 
 
                    $em->persist($dm); 
                } 
                  } 
              }elseif ($request->request->get('pickupScheduleCheckbox') == 'cueillette'){ 
            // if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) { 
            //   // dump($request->request->get("livraisonDate")) 
            //   $months = [ 
            //     'janvier' => 'january', 
            //     'février' => 'february', 
            //     'mars' => 'march', 
            //     'avril' => 'april', 
            //     'mai' => 'may', 
            //     'juin' => 'june', 
            //     'juillet' => 'july', 
            //     'août' => 'august', 
            //     'septembre' => 'september', 
            //     'octobre' => 'october', 
            //     'novembre' => 'november', 
            //     'décembre' => 'december' 
            //   ]; 
 
            //   $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3]; 
            //   $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate))); 
 
            //   $date = new \DateTime('now'); 
            //   $date->modify('+8 days'); 
 
            //   if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){ 
            //     $cart->setDeliveryChoiceDate($requestDate); 
            //     $cart->setPreOrder(true); 
            //     $cart->setPreOrderNow(true); 
            //   }else{ 
            //     $cart->setDeliveryChoiceDate($requestDate); 
            //     $cart->setPreOrder(true); 
            //   } 
            // } else { 
            //     $cart->setPreOrder(false); 
            //     $cart->setPreOrderNow(false); 
            //     $cart->setDeliveryChoiceDate(null); 
            // } 
 
                $pickUpSchedule = $request->get('pickupSchedule'); 
                if (empty($pickUpSchedule)) { 
                  $this->addFlash('error', "Il faut spécifier une date et un temps de cueillette."); 
                  return $this->redirectToRoute('adresse'); 
                } 
                $pickUpAdress = $request->get('pickupLocation'); 
                $pickupLocationId = $request->get('pickupLocations'); 
 
                $newAddress_phone = $request->request->get('pickup_phone'); 
                $newAdresse_name =  $request->request->get('pickup_name'); 
                if($cart->getPickupAddress() != null){ 
                  $UserInformation = $this->getUser(); 
                    $UserInformation->setPhone($newAddress_phone); 
                    $UserInformation->setFirstname($newAdresse_name); 
                  $em->persist($UserInformation); 
                  $em->flush(); 
                } 
                foreach($cart->getProducts() as $cp) { 
                  $dm = new DeliveryMethod(); 
                  $dm->setAverageDays(1); 
                  $dm->setIsAPickup(true); 
                  $dm->setServiceId(9999); 
                  $dm->setFixedPrice(0); 
                  $dm->setValid(true); 
                  $dm->setPickupSchedule($pickUpSchedule); 
                  $dm->setPickupAddress($pickUpAdress); 
                  $dm->setPickupLocationId($pickupLocationId); 
                  $cp->setCompanyDeliveryMethod($dm); 
                  $em->persist($dm); 
                  $em->persist($cp); 
                } 
              } 
              $estimationDateToTake = $cart->getShippingMaturinEstimatedDate(); 
              $contains_alcohol = false; 
              $contains_puro_exclusion = false; 
              $cold_products = false; 
              $products = []; 
       
              foreach($cart->getProducts() as $cp) { 
                $product = $cp->getProduct(); 
       
                if($product->getIsBoxOfProducts()) { 
                  foreach($product->getProductsInBox() as $mp) { 
                    $products[] = $mp->getProduct(); 
                    if ($mp->getProduct()->getPuroExclusion()) { 
                      $contains_puro_exclusion = true; 
                    } 
                  } 
                } else { 
                  $products[] = $product; 
                  if ($product->getPuroExclusion()) { 
                    $contains_puro_exclusion = true; 
                  } 
                } 
                if ($product->getIsCold()) { 
                  $cold_products = true; 
                } 
       
                if ($product->getIsAlcohol()) { 
                  $contains_alcohol = true; 
                } 
              } 
              $twigData['contains_alcohol'] = $contains_alcohol; 
              if ($cart->getShippingAddress() && $request->request->get('action_shipping') == 'domicile'){ 
                $cityName = $cart->getShippingAddress()->getCity(); 
                $province = $cart->getShippingAddress()->getProvince(); 
              }elseif($cart->getPickUpAddress() && $request->request->get('pickupScheduleCheckbox') == 'cueillette'){ 
                $completeAdresse = $cart->getPickUpAddress(); 
                $arrayAdresse = explode(',', $completeAdresse); 
                $cityName = trim($arrayAdresse[1]); 
                $province = trim($arrayAdresse[2]); 
              } 
              $city = $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province); 
 
              if ($city) { 
                $routes = $city[0]->getDeliveryRoutes(); 
                foreach($routes as $route) { 
                  if ( 
                    $route->getType() == "maturin" && $route->getName() != "Pas de frais" 
                  ) { 
                    $maturin_type_route_found = true; 
                  } 
                  if ($route->getName() == "Pas de frais") { 
                    $route_is_puro_nocold = true; 
                  } 
                } 
              } 
 
     
          $redirect_params = []; 
          if ($contains_puro_exclusion && !$maturin_type_route_found) { 
            // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool."); 
            $redirect_params["alert_nodelivery_puro"] = "true"; 
          } 
 
          if ($contains_alcohol && !$maturin_type_route_found) { 
            // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool."); 
            $redirect_params["alert_nodelivery_alcohol"] = "true"; 
          } 
 
          if ($route_is_puro_nocold && $cold_products && !$maturin_type_route_found) { 
            // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il doit rester frais durant la livraison."); 
            $redirect_params["alert_nodelivery_cold"] = "true"; 
          } 
 
          if (!empty($redirect_params) and $request->get('pickupScheduleCheckbox') != "cueillette" ) { 
            return $this->redirectToRoute('NewViewCart', $redirect_params); 
          } 
          if($cart->getShippingAddress()){ 
            $cart->calculateFees(); 
        } 
 
        // save cart changes 
        $em->persist($cart); 
        $em->flush(); 
        return $this->redirectToRoute('PaymentChoice');  
      } 
 
    }else{ 
      return $this->redirectToRoute('viewCart'); 
  } 
        return $twigData; 
    } 
 
 
 
     /** 
     * @Route({ 
     *          "fr": "/nouveauPaiement/maturinRecolte", 
     *          "en": "/newPayment/maturinRecolte" 
     *      }, name="RecapPayment") 
     * @Security("has_role('ROLE_USER')") 
     * @Template("frontend/newEndCheckoutPage.html.twig") 
     */ 
    public function RecapPayment(Request $request, PaymentService $paymentServ, UserService $userServ, UrlGeneratorInterface $router, DistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){ 
      $twigData = array(); 
      $twigData['hideSideMenu'] = true; 
      // $twigData['loader']= true; 
      $em = $this->getDoctrine()->getManager(); 
      $cart = $userServ->getCart(); 
      $user = $userServ->getUser(); 
      // dump($cart->getPickUpAddress()); 
      // if(empty($cart->getShippingAddress()) && empty($cart->getPickUpAddress())){ 
      //     $this->addFlash('error', "Nous avons d'abord besoin d'une adresse de livraison'"); 
      //     return $this->redirectToRoute('checkout'); 
      // } 
 
      if ($this->getUser() && $this->getUser()->getIsBetaTester() && count($cart->getProducts()) >0){ 
      $forceRedirect=false; 
      $route=[]; 
            foreach($cart->getProducts() as $p){ 
              if (!empty($route)){ 
                if ($twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') != $route['estimationDelivery']->format('Y-m-d') ){ 
                    $route[] = array( 
                      'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') 
                  ); 
                } 
              }else{ 
                $route = array( 
                  'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date'] 
                ); 
              }  
            } 
      sort($route); 
      $twigData['estimationDeliveryDate'] = $route; 
      /* 
       * Called when there is a Shipping Method change 
       * But not a payment 
       */ 
      if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){ 
          // if(!$cart->hasMaturinShipping()){ 
            if($cart->hasMaturinShipping()){ 
            $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart); 
          } 
 
          //Update the Shipping cost 
          if(!empty($twigData['shippingMaturin'])){ 
            $maturinShipping = current($twigData['shippingMaturin']); 
          } else { 
            $maturinShipping = false; 
          } 
          $found = false; 
      } 
       
      $shippingAddress = $cart->getShippingAddress(); 
      //We need a shipping address for the taxes 
      if($shippingAddress) { 
          $cart->calculateFees(); 
          $em->persist($cart); 
          $em->flush(); 
      } 
      $PuroTest = null; 
      if ($shippingAddress){ 
        $getMethodLivraisons = $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]); 
        foreach ($getMethodLivraisons as $getMethodLivraison) { 
          if ($getMethodLivraison->getType() == 'maturin') 
          $PuroTest = 'maturin'; 
        } 
      } 
      $twigData['puroConfirm'] = $PuroTest; 
 
      /* 
       * If payment is ready 
       */ 
      if($request->isMethod('post') && $request->request->get('pay_cart')){ 
          if(!empty($request->request->get('stripeToken'))) 
              $cart->setStripeToken($request->request->get('stripeToken')); 
 
               
              if ($cart->getUsedCoupon() == null){ 
                //Lets start with the coupon see if it's valid 
                  $coupon = $request->get("coupon"); 
                  if(!empty($coupon) ){ 
                    $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
                    $couponSearchTuango = false; 
                    $couponSearchTuango =  $this->CouponTuango($coupon); 
                    $couponCabane = false; 
                    $couponCabane =  $this->CouponCabaneMaturin($coupon); 
 
                    if ($couponSearchTuango != false || $couponCabane != false){ 
                      $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon); 
                    } 
                      if(empty($cartCoupon)){ 
                        if ($couponSearchTuango == false && $couponCabane == false){ 
                          $this->addFlash('error', "Merci de vérifier votre code coupon ou associez-le au bon produit"); 
                          return $this->redirectToRoute('checkout'); 
                        } 
                      }else{ 
                          //If coupon is a onetimeonly and was already used 
                          if($cartCoupon->getOneTimeOnly()){ 
                              if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){ 
                                  $this->addFlash('error', "Vous avez déja utilisé ce coupon"); 
                                  return $this->redirectToRoute('checkout'); 
                              } 
                          } 
                          //Check if any money left 
                          if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= 0 ){ 
                              $this->addFlash('error', "Ce coupon a un solde restant de 0$"); 
                              return $this->redirectToRoute('checkout'); 
                          } 
                          $cart->setUsedCoupon($cartCoupon); 
                          //$user = $userServ->getUser(); 
                          //$user->addCouponUsed($cartCoupon); 
                          //$em->persist($user); 
                      } 
                  }else{ 
                    //$user->removeCouponUsed($cartCoupon); 
                    $cart->setUsedCoupon(null); 
                  } 
              } 
 
              $em->persist($cart); 
              $em->flush(); 
          // if($request->request->get('NoteFromBuyer')){ 
          //   $noteFromBuyer = $request->request->get('NoteFromBuyer');  
          //   if (strlen($noteFromBuyer) <= 100){ 
          //     $patternNoteFromBuyer = '/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u'; 
          //     if(preg_match($patternNoteFromBuyer, 
          //       $noteFromBuyer 
          //     )){ 
          //        $noteFromBuyer = preg_replace($patternNoteFromBuyer,  
          //       '',  
          //       $noteFromBuyer); 
          //     } 
          //     $cart->setNoteFromBuyer($noteFromBuyer); 
          //   }else{ 
          //     $this->addFlash('error', "Veuillez ne pas dépasser les 100 characteres dans votre messages au livreur."); 
          //     return $this->redirectToRoute('checkout'); 
          //   } 
          // } 
          //Let's save if the signature was asked for the shipping 
          if (!empty($request->request->get('date_first_order'))){ 
            $date_first_order = $request->request->get('date_first_order'); 
          }else{ 
            $date_first_order = $cart->getShippingMaturinEstimatedDate(); 
          } 
          if (!empty($request->request->get('date_second_order'))){ 
            $date_second_order = $request->request->get('date_second_order'); 
          }else{ 
            $date_second_order = $cart->getShippingMaturinEstimatedDate(); 
          } 
           if($date_first_order && $date_second_order && $date_first_order != $date_second_order){ 
            $dates[]= $date_first_order; 
            $dates[]= $date_second_order; 
            $i=0; 
            foreach ($dates as $date) { 
              $customDeliveryDate = $date; 
              $months = [ 
                 'janvier' => 'january', 
                 'février' => 'february', 
                 'mars' => 'march', 
                 'avril' => 'april', 
                 'mai' => 'may', 
                 'juin' => 'june', 
                 'juillet' => 'july', 
                 'août' => 'august', 
                 'septembre' => 'september', 
                 'octobre' => 'october', 
                 'novembre' => 'november', 
                 'décembre' => 'december' 
               ]; 
 
               $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3]; 
               $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate))); 
 
               $date = new \DateTime('now'); 
               $date->modify('+8 days'); 
 
               if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){ 
                 $cart->setDeliveryChoiceDate($requestDate); 
                 $cart->setPreOrder(true); 
                 $cart->setPreOrderNow(true); 
               }else{ 
                 $cart->setDeliveryChoiceDate($requestDate); 
                 $cart->setPreOrder(true); 
               } 
 
                $separateCart = new Cart(); 
                $separateCart->setDateCreated($cart->getDateCreated()); 
                $separateCart->setDatePayment(new \Datetime('now')); 
                $separateCart->setUser($user); 
                $separateCart->setShippingAddress($cart->getShippingAddress()); 
                $separateCart->setDateCreated($cart->getDateCreated()); 
                $separateCart->setDateCreated($cart->getDateCreated()); 
                if($cart->hasMaturinShipping()){ 
                          $separateCart->setShippingMaturinCost($cart->getShippingMaturinCost()); 
                          $separateCart->setShippingMaturinCarrierName($cart->getShippingMaturinCarrierName()); 
                          $separateCart->setShippingMaturinServiceName($cart->getShippingMaturinServiceName()); 
                          $separateCart->setShippingMaturinServiceId($cart->getShippingMaturinServiceId()); 
                          $separateCart->setShippingMaturinEstimatedDate($cart->getShippingMaturinEstimatedDate()); 
                  } 
         
                    if ($i == 1){ 
                      foreach ($cart->getProducts() as $cartProduct ) { 
                        if ($cartProduct->getProduct()->getIsJustInTime()){ 
                          $separateCart->setIsOnHold(true); 
                          $cartProduct->setProduct($cartProduct->getProduct()); 
                          $separateCart->addProduct($cartProduct); 
                          dump('ok'); 
                        } 
                      } 
                    }else{ 
                      foreach ($cart->getProducts() as $cartProduct) { 
                        if(!$cartProduct->getProduct()->getIsJustInTime()){ 
                          $separateCart->setIsOnHold(false); 
                          $cartProduct->setProduct($cartProduct->getProduct()); 
                          $separateCart->addProduct($cartProduct); 
                        } 
                    } 
                  } 
                  $em->persist($cartProduct); 
                  $separateCart->setDeliveryChoiceDate($cart->getDeliveryChoiceDate()); 
                  $separateCart->setPreOrder($cart->getPreOrder()); 
                  $separateCart->setPreOrderNow($cart->getPreOrderNow()); 
                  $separateCart->setUsedCoupon($cart->getUsedCoupon()); 
                  $em->persist($separateCart); 
                  $em->flush(); 
              
 
                  if($paymentServ->payCart($separateCart)) { 
 
                    $locale = $request->getSession()->get('_locale'); 
                    if(empty($locale)) 
                        $locale = 'fr'; 
     
                    //if ($cart->getPreOrderNow() != true){ 
                      $newRoute = $router->generate( 'viewOrder', array ('_locale' => $locale, 'orderNo' => $separateCart->getOrderNo())); 
     
                      $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                      $this->addFlash('success', "Votre commande a été passée avec succès"); 
                  /* }else{ 
                      $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo())); 
     
                      $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                      $this->addFlash('success', "Votre commande a été passée avec succès"); 
                    }*/ 
     
                    $emailBody = $this->get('twig')->render('emails/order.html.twig', [ 
                        'cart' => $separateCart, 
                        'user' => $separateCart->getUser() 
                    ]); 
     
                    $replyTo = []; 
                    foreach ($separateCart->getProducts() as $cartProduct) { 
                        if (($association = $cartProduct->getAddedWhenBeingInAssociation()) != null) 
                        { 
                            foreach ($association->getAdminUsers() as $adminUser){ 
                                $replyTo[]=$adminUser->getEmail(); 
                            } 
                            foreach ($association->getUsersAddingCompanies() as $adminUser){ 
                                $replyTo[]=$adminUser->getEmail(); 
                            } 
                        } 
                      } 
     
                    $replyTo = count($replyTo) == 0 ? false : array_unique($replyTo); 
     
                    $userServ->sendEmail( 
                        'Confirmation de votre commande #'.$cart->getOrderNo(), 
                        $emailBody, 
                        false, 
                        $separateCart->getUser()->getEmail(), false, null, $replyTo 
                    ); 
     
                    //This happen if the cart contain JIT product OR the shipping estimate didn'T worked 
                    if(!$separateCart->getPreOrderNow()){ 
                      if(!$separateCart->getIsOnHold()){ 
                          //We are ready let's send the order 
                          if($separateCart->hasMaturinShipping() && !$distributorServ->sendOrders($separateCart)){ 
                              $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (hasMaturinShipping):'.$separateCart->getId(), 'Error with the Cart ID:'.$separateCart->getId() , 'entrepot@maturin.ca'); 
                          }else if($separateCart->isMaturinPickUp() && !$distributorServ->sendOrders($separateCart)){ 
                            $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (isMaturinPickUp):'.$separateCart->getId(), 'Error with the Cart ID:'.$separateCart->getId() , 'entrepot@maturin.ca'); 
                          } 
                      } 
                    } 
                   
                      $em->persist($separateCart); 
                      $em->flush(); 
                    /* 
                    * Let's see if it's the user first order 
                    * In this case, and he got a referrer we give him a coupon 
                    */ 
                    if($user->isFirstOrder() && !empty($user->getReferredBy())){ 
                        $coupon = new CartCoupon(); 
                        $coupon->setOneTimeOnly(true); 
                        $coupon->setType(0); 
                        $coupon->setAmount(10); 
                        $coupon->setCode('C-'.uniqid()); 
                        $coupon->setForUser($user->getReferredBy()); 
                        $coupon->setDateFrom(new \DateTime()); 
                        $coupon->setDateTo(new \DateTime("+1 year")); 
                        $em->persist($coupon); 
                    } 
     
                    //If it's a gift order let's remove the amount on it 
                    if(!empty($separateCart->getUsedCoupon()) && $separateCart->getUsedCoupon()->getIsGiftCertificate()){ 
                        $coupon = $separateCart->getUsedCoupon(); 
                        $separateCart->setAmountSavedByCoupon($separateCart->getCouponSavings()); 
                        $coupon = $coupon->setAmount($coupon->getAmount() - $separateCart->getTotal(false)); 
     
                        $em->persist($separateCart); 
                        $em->persist($coupon); 
                    } 
     
                    $em->flush(); 
     
                    if ($shippingAddress) { 
                      $cityName = $shippingAddress->getCity(); 
                      $province = $shippingAddress->getProvince(); 
                      if ($cityName && $province) { 
                        //$city = $em->getRepository(City::class)->findLikeName($cityName); 
                        $city = $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province); 
                        if (empty($city)) { 
                          // $cart->setIsOnHold(true); 
                          $em->persist($separateCart); 
                          $em->flush(); 
                          $userServ->sendEmail( 
                              'Ville invalide pour la commande #'.$cart->getOrderNo(), 
                              'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(), 
                              false, 
                              "info@maturin.ca", false, null, "info@maturin.ca" 
                          ); 
                        } 
                      } 
                    } 
     
                } else { 
                   
                    $this->addFlash('error', 'Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.'); 
                    return $this->redirectToRoute('cartPayment'); 
                } 
 
              $i++; 
            // $carts[]=$separateCart; 
          } 
          return $this->redirectToRoute('viewOrder', array('orderNo' => $separateCart->getOrderNo(), 'freshSale' => true)); 
 
          // foreach ($carts as $separateCart) { 
               
          // }          
           }else{ 
              // todo move from here 
              $signature = $request->request->get('signature-required'); 
              if($signature) 
                  $cart->setShippingSignatureRequired(true); 
              else 
                  $cart->setShippingSignatureRequired(false); 
                 
              $em->persist($cart); 
              $em->flush(); 
              /*---------------------------- en dessous insert la condition si champs preorder true alors envoi dans container preorders ---------------------------------------------*/ 
              if($paymentServ->payCart($cart)) { 
 
                // if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) { 
                //   // dump($request->request->get("livraisonDate")) 
                //   $months = [ 
                //     'janvier' => 'january', 
                //     'février' => 'february', 
                //     'mars' => 'march', 
                //     'avril' => 'april', 
                //     'mai' => 'may', 
                //     'juin' => 'june', 
                //     'juillet' => 'july', 
                //     'août' => 'august', 
                //     'septembre' => 'september', 
                //     'octobre' => 'october', 
                //     'novembre' => 'november', 
                //     'décembre' => 'december' 
                //   ]; 
 
                //   $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3]; 
                //   $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate))); 
 
                //   $date = new \DateTime('now'); 
                //   $date->modify('+8 days'); 
 
                //   if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){ 
                //     $cart->setDeliveryChoiceDate($requestDate); 
                //     $cart->setPreOrder(true); 
                //     $cart->setPreOrderNow(true); 
                //   }else{ 
                //     $cart->setDeliveryChoiceDate($requestDate); 
                //     $cart->setPreOrder(true); 
                //   } 
                // } else { 
                //     $cart->setPreOrder(false); 
                //     $cart->setPreOrderNow(false); 
                //     $cart->setDeliveryChoiceDate(null); 
                // } 
                  
 
                  $locale = $request->getSession()->get('_locale'); 
                  if(empty($locale)) 
                      $locale = 'fr'; 
 
                  //if ($cart->getPreOrderNow() != true){ 
                    $newRoute = $router->generate( 'viewOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo())); 
 
                    $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                    $this->addFlash('success', "Votre commande a été passée avec succès"); 
                /* }else{ 
                    $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo())); 
 
                    $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>'); 
                    $this->addFlash('success', "Votre commande a été passée avec succès"); 
                  }*/ 
 
                  $emailBody = $this->get('twig')->render('emails/order.html.twig', [ 
                      'cart' => $cart, 
                      'user' => $cart->getUser() 
                  ]); 
 
                  $replyTo = []; 
                  foreach ($cart->getProducts() as $cartProduct) { 
                      if (($association = $cartProduct->getAddedWhenBeingInAssociation()) != null) 
                      { 
                          foreach ($association->getAdminUsers() as $adminUser){ 
                              $replyTo[]=$adminUser->getEmail(); 
                          } 
                          foreach ($association->getUsersAddingCompanies() as $adminUser){ 
                              $replyTo[]=$adminUser->getEmail(); 
                          } 
                      } 
                    } 
 
                  $replyTo = count($replyTo) == 0 ? false : array_unique($replyTo); 
 
                  $userServ->sendEmail( 
                      'Confirmation de votre commande #'.$cart->getOrderNo(), 
                      $emailBody, 
                      false, 
                      $cart->getUser()->getEmail(), false, null, $replyTo 
                  ); 
 
                  //This happen if the cart contain JIT product OR the shipping estimate didn'T worked 
                  if(!$cart->getPreOrderNow()){ 
                    if(!$cart->getIsOnHold()){ 
                        //We are ready let's send the order 
                        if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){ 
                            $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (hasMaturinShipping):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                        }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){ 
                          $userServ->sendEmail('Maturin: Error Orders', 'Error with Cart ID (isMaturinPickUp):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca'); 
                        } 
                    } 
                  } 
                 
                    $em->persist($cart); 
                    $em->flush(); 
                  /* 
                  * Let's see if it's the user first order 
                  * In this case, and he got a referrer we give him a coupon 
                  */ 
                  if($user->isFirstOrder() && !empty($user->getReferredBy())){ 
                      $coupon = new CartCoupon(); 
                      $coupon->setOneTimeOnly(true); 
                      $coupon->setType(0); 
                      $coupon->setAmount(10); 
                      $coupon->setCode('C-'.uniqid()); 
                      $coupon->setForUser($user->getReferredBy()); 
                      $coupon->setDateFrom(new \DateTime()); 
                      $coupon->setDateTo(new \DateTime("+1 year")); 
                      $em->persist($coupon); 
                  } 
 
                  //If it's a gift order let's remove the amount on it 
                  if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){ 
                      $coupon = $cart->getUsedCoupon(); 
                      $cart->setAmountSavedByCoupon($cart->getCouponSavings()); 
                      $coupon = $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false)); 
 
                      $em->persist($cart); 
                      $em->persist($coupon); 
                  } 
 
                  $em->flush(); 
 
                  if ($shippingAddress) { 
                    $cityName = $shippingAddress->getCity(); 
                    $province = $shippingAddress->getProvince(); 
                    if ($cityName && $province) { 
                      //$city = $em->getRepository(City::class)->findLikeName($cityName); 
                      $city = $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province); 
                      if (empty($city)) { 
                        // $cart->setIsOnHold(true); 
                        $em->persist($cart); 
                        $em->flush(); 
                        $userServ->sendEmail( 
                            'Ville invalide pour la commande #'.$cart->getOrderNo(), 
                            'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(), 
                            false, 
                            "info@maturin.ca", false, null, "info@maturin.ca" 
                        ); 
                      } 
                    } 
                  } 
 
                  return $this->redirectToRoute('viewOrder', array('orderNo' => $cart->getOrderNo(), 'freshSale' => true)); 
              } else { 
                 
                  $this->addFlash('error', 'Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.'); 
                  return $this->redirectToRoute('cartPayment'); 
              } 
           } 
 
      } 
 
      // We set the coupon if users has a valid one 
          $couponMarketing= $this->session->get('coupon_marketing'); 
          $twigData['couponMarketing']=false; 
 
          if($couponMarketing){ 
            $cartCoupon = $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing); 
            if(!empty($cartCoupon)){ 
              $twigData['couponMaketing']=$cartCoupon; 
            } 
          } 
 
          $userCouponList=[]; 
          $tempCouponLists= $em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId()); 
          // we only get not used coupon by the user 
          foreach ($tempCouponLists as $cartCoupon ) { 
            if($cartCoupon->getOneTimeOnly()){ 
              if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())) 
                  continue; 
              else 
                array_push($userCouponList,$cartCoupon); 
            }else 
              array_push($userCouponList,$cartCoupon); 
          } 
 
          $twigData['couponLists'] = $userCouponList; 
         
      return $twigData; 
    }else{ 
      $this->addFlash('warning', 'Vous devez ajouter des produits'); 
      return $this->redirectToRoute('NewViewCart'); 
    } 
      
  } 
 
 
}