src/Controller/Frontend/WebsiteController.php line 2659

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  4. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use App\Entity\Orders;
  8. use App\Entity\OrderDetail;
  9. use App\Entity\OrderField;
  10. use App\Entity\ProductInventoryLog;
  11. use App\Entity\AlertPurchase;
  12. use App\Entity\Setting;
  13. use App\Entity\WebSlide;
  14. use App\Entity\WebSetting;
  15. use App\Entity\Brand;
  16. use App\Entity\Payment;
  17. use App\Entity\Product;
  18. use App\Entity\Category;
  19. use App\Entity\Subcategory;
  20. use App\Entity\Blog;
  21. use App\Entity\Customer;
  22. use App\Entity\Client;
  23. use App\Entity\CustomerLocation;
  24. use App\Service\PaymentQPayProHelper;
  25. use App\Service\PaymentNeoNetHelper;
  26. //use AppBundle\Helper\MailHelper;
  27. use App\Service\DistanceHelper;
  28. //use App\Helper\PaymentQPayProHelper;
  29. use Nzo\UrlEncryptorBundle\Annotations\ParamDecryptor;
  30. use Nzo\UrlEncryptorBundle\Annotations\ParamEncryptor;
  31. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  32. use Symfony\Component\Security\Core\Security;
  33. use App\Service\HelperService;
  34. use App\Service\MailHelper;
  35. use Symfony\Component\String\Slugger\SluggerInterface;
  36. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  37. use Doctrine\ORM\EntityManagerInterface;
  38. class WebsiteController extends AbstractController {
  39.     private $encryptor;
  40.     public function __construct(Encryptor $encryptor)
  41.     {
  42.         $this->encryptor $encryptor;    
  43.     }
  44.     
  45.     /**
  46.      *
  47.      * @Route("{slug}/store-product", name="frontend_store_product")
  48.      */
  49.     public function storeAction(Request $request$slug)
  50.     {
  51.         $em          $this->getDoctrine()->getManager();
  52.         //$userData    = $this->get("session")->get("userData");       
  53.         $currentCart json_decode($this->get("session")->get("cart"));
  54.         
  55.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);        
  56.         if($lastUsername)
  57.         {
  58.             $customerData $request->getSession()->get($lastUsername);
  59.         } else {
  60.             $customerData "";
  61.         }
  62.         /*
  63.         $newCart = array();
  64.         $this->get("session")->set("cart", json_encode($newCart));
  65.         $currentCart = json_decode($this->get("session")->get("cart"));
  66.         exit;
  67.         */
  68.         
  69.         if($currentCart)
  70.         {
  71.             if(count($currentCart) == 0)
  72.             {
  73.                 $currentCart = array();
  74.             }
  75.         } else {
  76.             $currentCart = array();
  77.         }
  78.         //print_r($currentCart);exit;
  79.         if($request->get('remove'))
  80.         {
  81.             $key $request->get('key');
  82.             $newCart = array();
  83.             foreach($currentCart as $thisKey => $cart)
  84.             {
  85.                 if($thisKey == $key)
  86.                 {
  87.                     
  88.                 } else {
  89.                     $newCart[] = $cart;
  90.                 }
  91.             }
  92.             $this->get("session")->set("cart"json_encode($newCart));
  93.             $currentCart json_decode($this->get("session")->get("cart"));
  94.         }
  95.         if($request->get('clean'))
  96.         {
  97.             $newCart = array();
  98.             $this->get("session")->set("cart"json_encode($newCart));
  99.             $currentCart json_decode($this->get("session")->get("cart"));
  100.         }
  101.         if($request->get('cart'))
  102.         {
  103.             $pid $request->get('pid');
  104.             $quantity $request->get('quantity');
  105.             $clientId 1;
  106.             $offerId  $request->get('oid','n');
  107.             $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
  108.             
  109.             $product $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
  110.                 'productId' => $pid
  111.             ));
  112.             
  113.             $newCart = array();
  114.             $currentCart json_decode($this->get("session")->get("cart"));
  115.             
  116.             //print_r($currentCart);exit;
  117.             if (!$this->get("session")->get("cart") || $this->get("session")->get("cart") == "[]")
  118.             {
  119.                 //print_r($currentCart);exit;
  120.                 $price  $product->getMainPrice();
  121.                 $o_name "";
  122.                 
  123.                 if($offerId)
  124.                 {                                    
  125.                     if($checkOffer)
  126.                     {     
  127.                         if($checkOffer['product_id'] != "" )
  128.                         {
  129.                             $o_name $checkOffer['offer_name'];                              
  130.                             $price $checkOffer['new_price'];     
  131.                         } else {                                         
  132.                             $discount = ($checkOffer['percent_discount']/100);
  133.                             $pricePercentage $product->getMainPrice()*$discount;                        
  134.                             $o_name $checkOffer['offer_name'];                              
  135.                             $price number_format($product->getMainPrice()-$pricePercentage2'.''');
  136.                         }
  137.                     }                    
  138.                 }                
  139.                 
  140.                 $newItem = array(
  141.                     'name'     => $product->getName(),
  142.                     'quantity' => $quantity,
  143.                     'price' => $price,
  144.                     'pid'   => $pid,
  145.                     'oid'   => $offerId,
  146.                     'o_name'=> $o_name,                       
  147.                     'img'   => $product->getMainPicture()
  148.                 );
  149.                 array_push($newCart$newItem);
  150.                 
  151.             } else {
  152.                 $foundPid = -1;
  153.                 foreach ($currentCart as $key => $cart)
  154.                 {
  155.                     if ($cart->pid == $pid) {
  156.                         //En que KEY esta el PID en cuestion?                    
  157.                         $foundPid $key;
  158.                     }
  159.                     
  160.                     $productObj $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
  161.                         'productId' => $cart->pid
  162.                     ));                    
  163.                     
  164.                     $price  $cart->price;
  165.                     $o_name $cart->o_name;
  166.                     if($cart->oid)
  167.                     {            
  168.                         $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($cart->oid);
  169.                         if($checkOffer)
  170.                         {     
  171.                             if($checkOffer['brand_id'] != "" || $checkOffer['category_id'] != "" || $checkOffer['subcategory_id'] != "" )
  172.                             {
  173.                                 $discount = ($checkOffer['percent_discount']/100);
  174.                                 $pricePercentage $productObj->getMainPrice()*$discount;
  175.                                 $o_name $checkOffer['offer_name'];
  176.                                 $price number_format($productObj->getMainPrice()-$pricePercentage2'.''');  
  177.                             } else {                             
  178.             
  179.                                 $o_name $checkOffer['offer_name'];
  180.                                 $price $checkOffer['new_price'];
  181.                 
  182.                             }    
  183.                                        
  184.                         }
  185.                     }
  186.                    
  187.                     $newItem = array(
  188.                         'name'     => $cart->name,
  189.                         'quantity' => $cart->quantity,
  190.                         'price' => $price,
  191.                         'pid'   => $cart->pid,
  192.                         'oid'   => $cart->oid,    
  193.                         'o_name'=> $o_name,   
  194.                         'img'   => $cart->img
  195.                     );
  196.                     
  197.                     array_push($newCart$newItem);
  198.                     
  199.                 }
  200.                 
  201.                 if ($foundPid == -1)
  202.                 {
  203.                     $price $product->getMainPrice();
  204.                     $o_name "";
  205.                     $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
  206.                     if($checkOffer)
  207.                     {     
  208.                         if($checkOffer['product_id'] != "")
  209.                         {                            
  210.                             $o_name $checkOffer['offer_name'];
  211.                             $price $checkOffer['new_price'];
  212.                         } else {    
  213.                         
  214.                             $discount = ($checkOffer['percent_discount']/100);
  215.                             $pricePercentage $product->getMainPrice()*$discount;
  216.                             $o_name $checkOffer['offer_name'];
  217.                             $price number_format($product->getMainPrice()-$pricePercentage2'.''');  
  218.                         } 
  219.                     }
  220.                     $newItem = array(
  221.                         'name' => $product->getName(),
  222.                         'quantity' => $quantity,
  223.                         'price' => $price,
  224.                         'pid' => $pid,
  225.                         'oid' => $offerId,
  226.                         'o_name'=> $o_name,   
  227.                         'img' => $product->getMainPicture()
  228.                     );
  229.                     array_push($newCart$newItem);
  230.                     
  231.                 } else {
  232.                     
  233.                     if ($quantity 0)
  234.                     {
  235.                         $newCart[$foundPid]['quantity'] = $quantity;
  236.                     } else {
  237.                         unset($newCart[$foundPid]);
  238.                     }
  239.                     
  240.                 }
  241.                 
  242.             }
  243.            
  244.             
  245.             $this->get("session")->set("cart"json_encode($newCart));
  246.             $currentCart $this->get("session")->get("cart");
  247.         }
  248.         $val 0;
  249.         $priceVal 0;
  250.         if (is_array($currentCart)) {
  251.             $currentCarts $currentCart;
  252.         } else {
  253.             $currentCarts json_decode($currentCart);
  254.         }
  255.         /*echo "<pre>";
  256.         print_r($currentCarts);
  257.         echo "</pre>";*/
  258.         $quitCoupon =false;    
  259.         foreach ($currentCarts as $cartTemp)
  260.         {
  261.             $val += $cartTemp->quantity;
  262.             $priceVal += $cartTemp->price $cartTemp->quantity;
  263.             //$val++;
  264.             if($cartTemp->oid != ''){
  265.                 $quitCoupon true;
  266.             }
  267.         }
  268.         //Verificamos configuración de cupones si hay productos con ofertas
  269.         
  270.         /*$client_id = $this->getParameter('client_id');
  271.         $client  = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  272.             "clientId" => $client_id
  273.         ));*/
  274.         
  275.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  276.             "slug" => $slug
  277.         ));
  278.         $client_id $client->getClientId();
  279.         
  280.         $setting  $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  281.             "Client" => $client
  282.         ));
  283.                    
  284.         if($quitCoupon && $setting->getCartAllowCouponWhithOffers() == '0'){
  285.              $this->get("session")->set("coupon",'');
  286.         }
  287.         $html "";
  288.         
  289.                 
  290.         if (is_array($currentCart)) {
  291.             $checkCart $currentCart;
  292.         } else {
  293.             $checkCart json_decode($currentCart);
  294.         }
  295.         if(count($checkCart) > 0)
  296.         {
  297.             
  298.             if ($priceVal 0) {
  299.                 $total 0;
  300.                 $grandTotal $priceVal;
  301.                 if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
  302.                     $coupon_id $this->get("session")->get("coupon");
  303.                     $couponObj $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
  304.                         "couponId" => $coupon_id
  305.                     ));
  306.                     $discount = ($priceVal $couponObj->getDiscountPercent())/100;
  307.                     $total $priceVal $discount;
  308.                     $grandTotal $total;
  309.                 }
  310.                 $finalPrice number_format($grandTotal2'.'',');
  311.             } else {
  312.                 $finalPrice '';
  313.             }
  314.             
  315.             //Aplicamos cupón
  316.             //$client_id = $this->getParameter('client_id');
  317.             $url $this->generateUrl('frontend_checkout', ['slug' => $slug]);
  318.             $information  $client;        
  319.             //Obtenemos simbolo de moneda a utilizar
  320.             $symbol $information->getCurrency()->getCurrencySymbol();
  321.             $html "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
  322.                 <i class='zmdi zmdi-shopping-cart'></i> $symbol$finalPrice
  323.                 <small class='cart_bottom_legend'>Clic aquí para terminar</small>
  324.             </div>";
  325.             
  326.         };
  327.         
  328.         if($customerData)
  329.         {
  330.             //Si esta autenticado el usuario, entonces se almacena todo el carrito que se tenga para tratar de
  331.             //hacer una recuperación despues
  332.             if($customerData['customer_id'])
  333.             {
  334.                 $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy([
  335.                     "customerId" => $customerData['customer_id']
  336.                 ]);
  337.                 $customerCartList $this->getDoctrine()->getRepository(\App\Entity\CustomerCart::class)->findBy([
  338.                     "created_by_customer_id" => $customerData['customer_id']
  339.                 ]);
  340.                 foreach($customerCartList as $cart)
  341.                 {
  342.                     $em->remove($cart);                    
  343.                     $em->flush();  
  344.                 }
  345.                                 
  346.                 foreach($currentCarts as $cart)
  347.                 {
  348.                     $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy([
  349.                         "productId" => $cart->pid
  350.                     ]);                        
  351.                     $customerCartObj = new \App\Entity\CustomerCart();
  352.                     $customerCartObj->setProduct($productObj);
  353.                     $customerCartObj->setClient($client);
  354.                     $customerCartObj->setPriceGiven($cart->price);
  355.                     $customerCartObj->setQuantity($cart->quantity);
  356.                     $customerCartObj->setIsActive(1);
  357.                     $customerCartObj->setCreatedAt(new \DateTime());
  358.                     $customerCartObj->setCreatedByCustomerId($customerObj);
  359.                     $em->persist($customerCartObj);
  360.                     $em->flush();  
  361.                 }
  362.                 
  363.             }
  364.         }
  365.         return new JsonResponse(array(
  366.             'slug'     => $slug,
  367.             'quantity' => $val,
  368.             'price'    => $priceVal,
  369.             'cart'     => $currentCarts,
  370.             'html'     => $html
  371.         ));
  372.     }
  373.     /**     
  374.      * @Route("{slug}/products", name="frontend_product")
  375.      */
  376.     public function productAction(Request $request$slug)
  377.     {
  378.         $em        $this->getDoctrine()->getManager();
  379.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  380.             "slug" => $slug
  381.         ));
  382.         $client_id $client->getClientId();
  383.         
  384.         $productCategory "";
  385.         $pager_limit     12;
  386.         $globalSearch    "";
  387.         $token           '';
  388.         $token2          '';
  389.         $brand           '';
  390.         $category        '';
  391.         $type            $request->get('type');
  392.         
  393.         if($request->get("token"))
  394.         {
  395.             $token $request->get('token');
  396.         }
  397.         if($request->get("token2"))
  398.         {
  399.             $token2 $request->get('token2');
  400.         }
  401.         if($request->get('search'))
  402.         {
  403.             $globalSearch $request->get('search');
  404.         }
  405.         if ($request->get('brand'))
  406.         {
  407.             $brand $request->get('brand');
  408.             $type 3;
  409.         }
  410.         
  411.         if($request->get('category'))
  412.         {
  413.             $category $request->get('category');
  414.             $type 3;
  415.         }
  416.         $filters = [
  417.             'token'     => $token,
  418.             'token2'    => $token2,
  419.             'type'      => $type,
  420.             'search'    => $globalSearch,
  421.             'brand'     => $brand,
  422.             'category'  => $category
  423.         ];
  424.         
  425.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  426.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  427.             "clientId" => $client_id
  428.         ));
  429.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  430.             "Client" => $client
  431.         ));
  432.         $query $em->getRepository(\App\Entity\Product::class)->getProducts($filters$client_id$settings->getCartHideEmptyStock());
  433.        
  434.         $subcategories $em->getRepository(\App\Entity\Subcategory::class)->findBy(array('is_active' => 1));
  435.         $categories $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
  436.         $total $em->getRepository(\App\Entity\Product::class)->getTotalCount();
  437.         
  438.         $webSetting $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array("Client" => $client_id));        
  439.         
  440.         // replace this example code with whatever you need
  441.         return $this->render('Frontend/Product/index.html.twig', array(
  442.             'list' => $query,
  443.             'pager_limit'     => $pager_limit,
  444.             'subcategories'   => $subcategories,
  445.             'categories'      => $categories,
  446.             'productCategory' => $productCategory,
  447.             'globalSearch'    => $globalSearch,
  448.             'webSetting'      => $webSetting,
  449.             'brand'           => $brand,
  450.             'category'        => $category,
  451.             'slug'              => $slug
  452.         ));
  453.     }
  454.     
  455.     
  456.     // @Route("/product/direct/{id}", name="frontend_product_direct")*/
  457.     /**
  458.     * @Route("{slug}/product_view/{productId}", name="frontend_product_index")
  459.     * @ParamDecryptor({"productId"})
  460.     */
  461.     public function productDirectAction(Request $requestProduct $product$slug) {
  462.         $em $this->getDoctrine()->getManager();
  463.         $client_id $this->getParameter('client_id');
  464.         
  465.         //$productObj = $em->getRepository(Product)->findProductByMd5Id($id);
  466.         //if($productObj)
  467.         //{
  468.             
  469.     
  470.             //$product = $em->getRepository('AppBundle:Product')->findOneBy(array('productId' => $productObj['product_id']));    
  471.             $serverName $_SERVER['SERVER_NAME'];    
  472.             $product_id $product->getProductId();
  473.             return $this->render('Frontend/Product/product_direct.html.twig', array(
  474.                 'product_id' => $product_id,
  475.                 'product'    => $product,
  476.                 'brand'      => '',
  477.                 'slug'       => $slug,
  478.                 'category'   => '',
  479.                 'productCategory' => '',
  480.                 'pager_limit'     => 12,
  481.                 'globalSearch'    => '',
  482.                 'serverName'      => $serverName
  483.             ));
  484.             
  485.         //} else {
  486.             //return $this->redirectToRoute("frontend_index");
  487.         //}
  488.         
  489.     }
  490.     
  491.     
  492.         
  493.     
  494.     /**
  495.      *
  496.      * @Route("{slug}/product-modal-load", name="frontend_product_modal_load")
  497.      */
  498.     public function productModalLoadAction(Request $request$slug)
  499.     {
  500.         $em $this->getDoctrine()->getManager();
  501.         
  502.         $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  503.             "slug" => $slug
  504.         ]);
  505.         $client_id $information->getClientId();
  506.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  507.         $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
  508.             "Client" => $information
  509.         ]);
  510.         $query $em->getRepository(\App\Entity\Product::class)->getOneProduct($request->get('id'),$setting->getCartHideEmptyStock());
  511.         
  512.         
  513.         //VERIFICAMOS HORARIOS
  514.         $store_status 'open';               
  515.         $day_number date('N');
  516.         $hoursToday $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$client_id);        
  517.         if($hoursToday['is_open'] == '0')
  518.         {
  519.            $store_status    'closed';                  
  520.         }
  521.         $customerData '';
  522.         if($this->get("session")->get("userData"))
  523.         {
  524.             $customerData $this->get("session")->get("userData");
  525.         }    
  526.         // replace this example code with whatever you need
  527.         return $this->render('Frontend/_modal_content_product.html.twig', array(
  528.             'item'           => $query
  529.             'setting'        => $setting,
  530.             'information'    => $information,
  531.             'store_status'   => $store_status,
  532.             'customerData'   => $customerData,
  533.             'slug'           => $slug
  534.         ));
  535.     }
  536.     /**
  537.      *
  538.      * @Route("{slug}/get-product", name="frontend_get_product")
  539.      */
  540.     public function getProductAction(Request $request$slug)
  541.     {
  542.         $em $this->getDoctrine()->getManager();
  543.         
  544.         //$client_id = $this->getParameter('client_id');
  545.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(["slug" => $slug]);
  546.         $client_id $client->getClientId();
  547.         $pager_limit  12;
  548.         $globalSearch "";
  549.         $token '';
  550.         if($request->get("token"))
  551.         {
  552.             $token $request->get('token');
  553.         }
  554.         
  555.         $token2 '';
  556.         if($request->get("token2"))
  557.         {
  558.             $token2 $request->get('token2');
  559.         }
  560.         if($request->get('search'))
  561.         {
  562.             $globalSearch $request->get('search');
  563.         }
  564.         $filters = [
  565.             'token'  => $token,
  566.             'token2' => $token2,
  567.             'type'   => $request->get('type'),
  568.             'search' => $globalSearch,
  569.             'limit'  => $request->get('limit')
  570.         ];
  571.         
  572.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  573.         $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(["Client" => $client]);        
  574.         $query   $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock());
  575.         
  576.         $subcategories $em->getRepository(\App\Entity\Subcategory::class)->findBy(['is_active' => 1]);
  577.         $categories    $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
  578.         $total         $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock(),true);
  579.         
  580.        
  581.         
  582.         // replace this example code with whatever you need
  583.         return $this->render('Frontend/product_items.html.twig', array(
  584.             'list' => $query,
  585.             'pager_limit'   => $pager_limit,
  586.             'subcategories' => $subcategories,
  587.             'categories'    => $categories,
  588.             'product_count' => count($total),
  589.             'globalSearch'  => $globalSearch,
  590.             'isMore'        => $request->get('isMore'),
  591.             'setting'       => $setting,
  592.             'slug'          => $slug,
  593.             'information'   => $client
  594.                 
  595.         ));
  596.     }
  597.     /**
  598.      *
  599.      * @Route("/start/token={id}", name="frontend_start")
  600.      */
  601.     public function startAction(Request $request) {
  602.         if($request->get('id') == 'c4ca4238a0b923820dcc509a6f75849b')
  603.         {
  604.             $valor "25";
  605.         } elseif ($request->get('id') == 'c81e728d9d4c2f636f067f89cc14862c')
  606.         {
  607.             $valor "58";
  608.         } elseif ($request->get('id') == 'eccbc87e4b5ce2fe28308fd9f2a7baf3')
  609.         {
  610.             $valor "39";
  611.         }
  612.         return $this->render('Frontend/Index/start.html.twig', array(
  613.             "valor" => $valor
  614.         ));
  615.     }
  616.     /**
  617.      * @Route("{slug}/blogs", name="frontend_blog")
  618.      */
  619.     public function blogAction(Request $request$slug)
  620.     {
  621.         
  622.         // replace this example code with whatever you need
  623.         $categories $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);
  624.         return $this->render('Frontend/Blog/blog.html.twig', array(
  625.             'categories'      => $categories,
  626.             'slug'            => $slug,
  627.             'productCategory' => '',
  628.             'pager_limit'     => 12,
  629.             'globalSearch'    => '',
  630.             'brand'           => '',
  631.             'category'        => ''
  632.         ));
  633.     }
  634.     /**     
  635.      * @Route("{slug}/blog/load-items", name="frontend_blog_items")
  636.      */
  637.     public function blogLoadAction(Request $request$slug)
  638.     {   
  639.         $em        $this->getDoctrine()->getManager();
  640.         $desde     $request->get('desde');
  641.         $hasta     $request->get('hasta');
  642.         $categoria $request->get('categoria');
  643.         
  644.         //$client_id = $this->getParameter('client_id');
  645.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
  646.         $client_id $client->getClientId();
  647.         
  648.         $blogs $em->getRepository(\App\Entity\Blog::class)->listBlog($desde$hasta$categoriafalse$client_id);
  649.         $blogs_total $em->getRepository(\App\Entity\Blog::class)->listBlog($desde$hasta$categoriatrue$client_id);
  650.         $blogs_count $em->getRepository(\App\Entity\Blog::class)->listBlog(0,($desde+$hasta), $categoriafalse$client_id);
  651.         return $this->render('Frontend/Blog/load_items_blog.html.twig',array(
  652.             "list"  => $blogs,
  653.             "slug"  => $slug,
  654.             "count" => count($blogs_count),
  655.             "total" => count($blogs_total)
  656.         ));
  657.     }
  658.     /**     
  659.      * @Route("{slug}/blog/detail/{blogId}", name="frontend_blog_detail")
  660.      * @ParamDecryptor({"blogId"})
  661.      */
  662.     public function blogDetailAction(Request $requestBlog $blog$slug)
  663.     {   
  664.         
  665.         //$category = $this->getDoctrine()->getRepository('AppBundle:BlogCategory')->findBy(array("isActive" => '1'));
  666.         return $this->render('Frontend/Blog/blog_detail.html.twig',array(
  667.             "blog"              => $blog,
  668.             "slug"              => $slug,
  669.             'productCategory'   => '',
  670.             'pager_limit'       => 12,
  671.             'globalSearch'      => '',
  672.             'brand'             => '',
  673.             'category'          => ''
  674.         ));
  675.     }
  676.  
  677.    
  678.     /**
  679.      * @Route("/check", name="frontend_check" )
  680.      */
  681.     public function checkAction(Request $request) {
  682.         return new JsonResponse(array(
  683.             'status' => 'success'
  684.         ));
  685.     }
  686.     /**
  687.      * @Route("/process", name="frontend_process" )
  688.      */
  689.     public function processAction(Request $request) {
  690.         var_dump($request);
  691.         die;
  692.         return new JsonResponse(array(
  693.             'status' => 'success'
  694.         ));
  695.     }
  696.     /**
  697.      *
  698.      * @Route("{slug}/checkout", name="frontend_checkout")
  699.      */
  700.     public function checkoutAction(Request $request$slug)
  701.     {
  702.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  703.         
  704.         $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  705.             "slug" => $slug
  706.         ]);
  707.         $client_id   $information->getClientId();
  708.         if(!$information)
  709.         {
  710.             return $this->redirectToRoute("homepage_website", ['slug' => $slug]);
  711.         }
  712.         $currentCart $this->get("session")->get("cart");
  713.         if($currentCart)
  714.         {
  715.             
  716.         } else {
  717.             return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
  718.         }
  719.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
  720.             "Client" => $information
  721.         ]);
  722.         
  723.         $customerData '';                
  724.         if($lastUsername)
  725.         {
  726.             $customerData $request->getSession()->get($lastUsername);
  727.         }    
  728.         
  729.         $coupon '';
  730.         if($this->get("session")->get("coupon"))
  731.         {
  732.             $coupon $this->get("session")->get("coupon");
  733.         }
  734.         
  735.                 
  736.         $day_number   date('N');
  737.         $store_status "open";
  738.         
  739.         $client         $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(["clientId" => $client_id]);
  740.         $hoursToday     $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$client_id);
  741.         $paymentMethods $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findBy([
  742.             'Client'     => $client,
  743.             'is_display' => 1,
  744.             'is_active'  => 1
  745.         ]);        
  746.         $paymentCardObj $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy([
  747.             'Client'    => $client,
  748.             'is_active' => 1,
  749.             'is_cash'   => 0
  750.         ]); 
  751.                 
  752.         if($hoursToday['is_open'] == '0')
  753.         {
  754.             $store_status "closed";
  755.         }
  756.         
  757.         $session_uniq_id uniqid();
  758.         
  759.         $org_id       "";
  760.         $random_value "";
  761.         if($paymentCardObj->getPaymentMethodGateway())
  762.         {
  763.             //QPAYPRO es gateway 1
  764.             if($paymentCardObj->getPaymentMethodGateway()->getPaymentMethodGatewayId() == 1)
  765.             {
  766.                 $org_id       "1snn5n9w";
  767.                 $random_value "visanet_qpay"."1618";
  768.                 
  769.                 //Esta bandera es para definir si es PROD o no
  770.                 //Get Field Token Tertiary es igual al public Key
  771.                 if($paymentCardObj->getIsProd())
  772.                 {            
  773.                     $org_id       "k8vif92e";
  774.                     $random_value $paymentCardObj->getFieldTokenTertiary()."1618";
  775.                 }
  776.             }    
  777.         }        
  778.         
  779.         $storedCards = [];
  780.         if($customerData)
  781.         {
  782.             $storedCards $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findBy([
  783.                 'Customer'  => $customerData['customer_id'],
  784.                 'is_active' => 1                
  785.             ]); 
  786.         }
  787.         
  788.         return $this->render('Frontend/Checkout/checkout.html.twig', [
  789.             'productCategory' => '',
  790.             'pager_limit'     => 12,
  791.             'globalSearch'    => '',
  792.             'slug'            => $slug,
  793.             'settings'        => $settings,
  794.             'information'     => $information,
  795.             'coupon'          => $coupon,
  796.             'customerData'    => $customerData,
  797.             'brand'           => '',
  798.             'category'        => '',
  799.             'store_stataus'   => $store_status,
  800.             'client_id'       => $client_id,
  801.             'payment_methods' => $paymentMethods,
  802.             'session_uniq_id' => $session_uniq_id,
  803.             'random_value'    => $random_value,
  804.             'org_id'          => $org_id,
  805.             'storedCards'     => $storedCards            
  806.         ]);
  807.     }
  808.     /**
  809.      * @Route("{slug}/email_test", name="frontend_checkout_emailtest")
  810.      */
  811.     public function emailTest(Request $requestMailHelper $MailHelper)
  812.     {
  813.         exit;
  814.         $textMessage str_replace('_TABLA_PEDIDOS_''<br>PEDIDOS PEDIDOS PEDIDOS',"Hola hola hola");
  815.         $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  816.             'emailTitle'    =>  "Prueba Email",
  817.             'logoPath'      =>  "https://dev.aguilalibreweb.com/2308/ecommerce_aguila/public/uploads/12/web/30724402820250820002840.png",
  818.             'message'       =>  $textMessage,
  819.             'footer1'       =>  "footer",       
  820.             'user'          =>  '',
  821.             'rootWebUrl'    =>  "rootURL"
  822.         ) )->getContent();
  823.         $debug $MailHelper->sendEmail("Nombre de Tienda","servicio@aguilalibreweb.com""Prueba Email"$myMessage"");
  824.         return new JsonResponse(array(
  825.             'status'  => 'success',
  826.             'orderId' => $debug
  827.         ));
  828.         
  829.     }
  830.     
  831.     
  832.     /**
  833.      *
  834.      * @Route("/checkout/execute", name="frontend_checkout_execute")
  835.      */
  836.     public function checkoutExecuteAction(Request $requestMailHelper $MailHelper)
  837.     {
  838.         
  839.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  840.         $userData false;
  841.         if($lastUsername)
  842.         {
  843.             $userData $request->getSession()->get($lastUsername);        
  844.         }
  845.         $em $this->getDoctrine ()->getManager ();
  846.         $client_id $this->getParameter('client_id');
  847.         
  848.         $data           $request->get('query');
  849.         $payment_method $request->get('payment_method');
  850.         $dummy_order_id $request->get('auth');
  851.         /*echo "<pre>";
  852.         print_r($data);
  853.         echo "</pre>";        
  854.         exit;*/
  855.         $userData $this->get("session")->get("userData");
  856.         $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  857.             "clientId" => $client_id
  858.         ));        
  859.         $webSetting  $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array(
  860.             "Client" => $information
  861.         ));        
  862.         
  863.         //Obtenemos simbolo de moneda a utilizar
  864.         $symbol $information->getCurrency()->getCurrencySymbol();
  865.         
  866.         $payment  $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  867.             "paymentMethodId" => $payment_method
  868.         ));        
  869.         $orderStatus  $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
  870.             "orderStatusId" => 1
  871.         ));                
  872.         $deliveryCharge "";
  873.         if($request->get("delivery_price"))
  874.         {
  875.             $deliveryCharge $request->get("delivery_price");            
  876.         }
  877.         $orders = new Orders();
  878.         $orders->setOrderType('cart');
  879.         $orders->setDeliveryCharge($deliveryCharge);
  880.         $orders->setPaymentMethod($payment);
  881.         $orders->setServiceFee($information->getServiceFee());
  882.         
  883.         if($userData)
  884.         {
  885.             $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
  886.                 "customerId" => $userData['customer_id']
  887.             ));
  888.             $orders->setCustomer($customerObj);
  889.         }
  890.         
  891.         $orders->setIsActive(1);
  892.         $orders->setClient($information);
  893.         $orders->setOrderStatus($orderStatus);
  894.         $orders->setCreatedAt(new \DateTime());
  895.         $em->persist($orders);
  896.         $em->flush();     
  897.         if($orders)
  898.         {
  899.             $currentCart  $this->get("session")->get("cart");
  900.             $cartList     json_decode($currentCart);                    
  901.             $orderDetailMail ="<table style='width:100%;text-align: left!important;'>
  902.                                 <tr style='border-bottom:1px solid #ccc'>
  903.                                 <th>Productos</th><th></th>
  904.                                 </tr>";
  905.             $totalOrder 0;
  906.             if(count($cartList) > 0)
  907.             {        
  908.                 foreach($cartList as $cart)
  909.                 {
  910.                     $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  911.                         "productId" => $cart->pid
  912.                     ));
  913.                     $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  914.                         "offerId" => $cart->oid
  915.                     ));                                
  916.                 
  917.                     $orderDetail = new OrderDetail();
  918.                     $orderDetail->setOrder($orders);
  919.                     $orderDetail->setProduct($productObj);
  920.                     $orderDetail->setQuantity($cart->quantity);
  921.                     $orderDetail->setPriceGiven($cart->price);
  922.                     $orderDetail->setOriginalPrice($productObj->getMainPrice());                                        
  923.                     $orderDetail->setCreatedAt(new \DateTime());
  924.                     
  925.                     $totalPrice $cart->quantity*$cart->price;
  926.                     $totalOrder $totalOrder $totalPrice;
  927.                     $orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>                          
  928.                         <td style='padding:10px;text-align: left!important;'>
  929.                             <img style='height:80px' src='".$productObj->getMainPicture()."' >
  930.                         </td>
  931.                             <td style='padding:10px;text-align: left!important;'>
  932.                                 ".$productObj->getName()."<br>
  933.                                 $symbol.$cart->price x $cart->quantity = <b>$symbol.".number_format($totalPrice2'.''')."</b><br>                                         
  934.                             
  935.                         ";
  936.                     
  937.                     if($cart->oid)
  938.                     {
  939.                         $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  940.                             "offerId" => $cart->oid
  941.                         ));            
  942.                         $orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
  943.                         $orderDetail->setOffer($offerObj);
  944.                     }
  945.                     $orderDetailMail.="</td></tr>";
  946.                     $em->persist($orderDetail);
  947.                     $em->flush();            
  948.                     
  949.                     //RESTAMOS DE INVENTARIO
  950.                     
  951.                     if($productObj->getHasInventory())
  952.                     {
  953.                         $productInventory $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
  954.                             "Product" => $productObj
  955.                         ));                                                
  956.                         if($productInventory)
  957.                         {
  958.                             $oldStock $productInventory->getAvailable();
  959.                             $stock $oldStock $cart->quantity;
  960.                             $productInventory->setAvailable($stock);
  961.                             $em->persist($productInventory);
  962.                             $em->flush();    
  963.                             $productInventoryLog = new ProductInventoryLog();
  964.                             $productInventoryLog->setProduct($productObj);
  965.                             $productInventoryLog->setCreatedAt(new \DateTime());
  966.                             $productInventoryLog->setOrderDetail($orderDetail);
  967.                             $productInventoryLog->setSelledQuantity($cart->quantity);
  968.                             $em->persist($productInventoryLog);
  969.                             $em->flush();
  970.                         }
  971.                     }
  972.                 }
  973.             }
  974.             $orderDetailMail.="</table>";   
  975.             $grandTotal $totalOrder;
  976.             $orders->setTotalOriginal($grandTotal);
  977.             if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
  978.             {
  979.                 $coupon_id $this->get("session")->get("coupon");
  980.                 $couponObj $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
  981.                     "couponId" => $coupon_id
  982.                 ));
  983.                 $discount = ($totalOrder $couponObj->getDiscountPercent())/100;
  984.                 $total $totalOrder $discount;
  985.                                 
  986.                 $grandTotal $total;
  987.                 $orders->setTotal(number_format($total2'.'','));
  988.                 $orders->setCoupon($couponObj);
  989.                 $this->get("session")->set("coupon"'');
  990.                 $orderDetailMail.="<center><table>
  991.                     <tr><td style='width:150px;text-align: left!important;'><b style='color:#ccc'>Cupón aplicado: </b></td><td style='text-align: left!important;' >".$couponObj->getCouponCode()."</td></tr>
  992.                     <tr><td style='text-align: left!important;'><b style='color:#ccc'>Subtotal: </b></td><td style='text-align: left!important;'> $symbol.".$total."</td></tr>
  993.                     <tr><td style='text-align: left!important;'><b style='color:#ccc'>Descuento: </b></td><td style='text-align: left!important;'> $symbol.".number_format($discount2'.'',')." <b>-".$couponObj->getDiscountPercent()."%</b></td></tr></table></center>";                 
  994.             
  995.             } else {
  996.                 $orders->setTotal(number_format($totalOrder2'.'','));
  997.             }
  998.         
  999.             $em->persist($orders);
  1000.             $em->flush();   
  1001.                     
  1002.             if($deliveryCharge == 'N')
  1003.             {
  1004.                 $orderDetailMail.="<p  style='color:tomato'>No se pudo calcular el cargo por la entrega automáticamente.Cargos de entrega podrían aplicar posterior a la confirmación de su pedido.</p>";
  1005.             } else if($deliveryCharge == 'FREE')
  1006.             {
  1007.                 $orderDetailMail.="<p  style='color:tomato'>¡Envío Gratis!</p>";
  1008.             } else if($deliveryCharge != "")
  1009.             {
  1010.                 $orderDetailMail.="<p style='color:tomato'>+Cargo de envío: <b>$symbol.".number_format($deliveryCharge2'.'',')."</b></p>";
  1011.             }
  1012.             //Se agrega el service fee
  1013.             if($information->getServiceFee() > 0)
  1014.             {                
  1015.                 $grandTotal $grandTotal $information->getServiceFee();
  1016.             }            
  1017.             $orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal2'.'',')." </h3>";
  1018.             
  1019.             $purchaserValue "";
  1020.             $emailAnonymous="";
  1021.         
  1022.             foreach($data['purchaser'] as $purchaser)
  1023.             {
  1024.                     
  1025.                 if($purchaser['is_email'] == true){
  1026.                     $emailAnonymous $purchaser['value']; 
  1027.                 }
  1028.             
  1029.                 $fieldClientObj $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
  1030.                     "fieldClientId" => $purchaser['field_client_id']
  1031.                 ));    
  1032.                 $fieldTypeObj $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
  1033.                     "fieldTypeId" => $purchaser['field_type_id']
  1034.                 ));                                
  1035.                 $orderField = new OrderField();
  1036.                 $orderField->setOrder($orders);
  1037.                 $orderField->setFieldClient($fieldClientObj);
  1038.                 $orderField->setFieldType($fieldTypeObj);
  1039.                 $orderField->setName($purchaser['name']);
  1040.                 if($purchaser['field_type_id'] == 3)
  1041.                 {
  1042.                     $fieldValueObj $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
  1043.                         "fieldValueId" => $purchaser['value']
  1044.                     ));    
  1045.                     if($fieldValueObj)
  1046.                     {
  1047.                         $orderField->setFieldValue($fieldValueObj);                    
  1048.                     }
  1049.                 } else if($purchaser['field_type_id'] == 4)
  1050.                 {
  1051.                         $lat $purchaser['value']['lat'];
  1052.                         $lng $purchaser['value']['lng'];                    
  1053.                         $orderField->setValueText("$lat,$lng");                    
  1054.                 } else {
  1055.                         $orderField->setValueText($purchaser['value']);                    
  1056.                 }
  1057.                 /* --- DELIVERY OR PICKUP --- */
  1058.                 $mailStore "";
  1059.                 if($purchaser['field_type_id'] == 9)
  1060.                 {
  1061.                         
  1062.                         $storeObj $this->getDoctrine()->getRepository(\App\Entity\Store::class)->findOneBy(array(
  1063.                             "storeId" => $purchaser['value']
  1064.                         ));                            
  1065.                         $orders->setStore($storeObj);
  1066.                         $em->persist($orders);
  1067.                         $em->flush();         
  1068.                         
  1069.                         //Dinamica para enviar EMAIL a la tienda si acaso esta activada la opción
  1070.                         $mailStore $storeObj->getEmail();
  1071.                 } 
  1072.                 /* --- DELIVERY OR PICKUP --- */
  1073.                 $orderField->setCreatedAt(new \DateTime());                
  1074.                 $em->persist($orderField);
  1075.                 $em->flush();                
  1076.             }        
  1077.             //ENVÍO DE EMAIL
  1078.             
  1079.             $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1080.                 "clientId" => $client_id
  1081.             ));
  1082.             $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1083.                 "Client" => $client
  1084.             ));        
  1085.             $MailHelper = new MailHelper();   
  1086.             $rootWebUrl =  $MailHelper->getRootWebAppURL("0");
  1087.             $subject 'Nuevo pedido registrado #'.$orders->getOrderId();
  1088.             $textMessage $setting->getTemplateConfirmationOrders();
  1089.             $array_cc = array();
  1090.             $mails_sent "";
  1091.             if($userData)
  1092.             {
  1093.                 $mailTo =  $customerObj->getEmail();  
  1094.                 $mailCopy $setting->getEmailNotificationOrder();
  1095.                 $mails_sent=$mailTo.",".$mailCopy;
  1096.             } else {
  1097.                 if($emailAnonymous != '')
  1098.                 {
  1099.                     $mailTo $emailAnonymous;
  1100.                     $mailCopy $setting->getEmailNotificationOrder();
  1101.                     $mails_sent=$mailTo.",".$mailCopy;
  1102.                 } else {
  1103.                     $mailTo $setting->getEmailNotificationOrder();
  1104.                     $mails_sent=$mailTo;
  1105.                     $mailCopy null;
  1106.                 }
  1107.             }
  1108.             
  1109.             
  1110.             $footer1 =  null;
  1111.             
  1112.             $textMessage str_replace('_TABLA_PEDIDOS_''<br>'.$orderDetailMail$textMessage);
  1113.             $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  1114.                 'emailTitle'    =>  $subject,
  1115.                 'logoPath'      =>  $webSetting->getLogoPath(),
  1116.                 'message'       =>  $textMessage,
  1117.                 'footer1'       =>  $footer1,                   
  1118.                 'user'          =>  '',
  1119.                 'rootWebUrl'    =>  $rootWebUrl
  1120.             ) )->getContent();
  1121.             $MailHelper->sendEmail($client->getName(), $mailTo$subject$myMessage$mailCopy$mailStore);
  1122.             
  1123.             
  1124.             //Guardamos log de envío de alerta
  1125.             $alertPurchase = new AlertPurchase();
  1126.             $alertPurchase->setClient($client);
  1127.             $alertPurchase->setCreatedAt(new \DateTime());
  1128.             $alertPurchase->setEmailSent($mails_sent);
  1129.             $alertPurchase->setIsActive(1);
  1130.             $alertPurchase->setOrder($orders);
  1131.             $em->persist($alertPurchase);
  1132.             $em->flush();    
  1133.             
  1134.             //Si la compra se proceso correctamente entonces guardamos el id de la orden en la tabla payment
  1135.             if($payment->getIsCash() != '1' && $dummy_order_id != '0')
  1136.             {
  1137.                 $paymentRegister $this->getDoctrine()->getRepository(\App\Entity\Payment::class)->findOneBy(array(
  1138.                     "custom_auth_code" => $dummy_order_id
  1139.                 ));                
  1140.                 $paymentRegister->setOrder($orders);
  1141.                 $em->persist($paymentRegister);
  1142.                 $em->flush();
  1143.             }
  1144.             
  1145.             $orderIdEncoded $this->encryptor->encrypt($orders->getOrderId());
  1146.             
  1147.             return new JsonResponse(array(
  1148.                 'status'  => 'success',
  1149.                 'orderId' => $orderIdEncoded
  1150.             ));
  1151.             
  1152.         } else {
  1153.             
  1154.             return new JsonResponse(array(
  1155.                 'status'  => 'error',
  1156.                 'orderId' => ''
  1157.             ));            
  1158.             
  1159.         }
  1160.                 
  1161.     }
  1162.     /**
  1163.      *
  1164.      * @Route("/checkout/direct-execute", name="frontend_checkout_direct_execute")
  1165.      */
  1166.     public function checkoutDirectExecuteAction(Request $request)
  1167.     {
  1168.         
  1169.                 $em $this->getDoctrine ()->getManager ();
  1170.                 $client_id  $this->getParameter('client_id');
  1171.                 $product_id $request->get('product_id');
  1172.                 $offer_id   $request->get('offer_id');
  1173.                 $price      $request->get('price');
  1174.                 $data       $request->get('query');
  1175.                 $userData $this->get("session")->get("userData");
  1176.                 $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1177.                     "clientId" => $client_id
  1178.                 ));        
  1179.                 //Obtenemos simbolo de moneda a utilizar
  1180.                 $symbol $information->getCurrency()->getCurrencySymbol();
  1181.                 $payment  $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  1182.                     "paymentMethodId" => 1
  1183.                 ));        
  1184.                 $orderStatus  $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
  1185.                     "orderStatusId" => 1
  1186.                 ));
  1187.                 $orders = new Orders();
  1188.                 $orders->setOrderType('direct');
  1189.                 $orders->setPaymentMethod($payment);
  1190.                 if($userData)
  1191.                 {
  1192.                         $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
  1193.                             "customerId" => $userData['customer_id']
  1194.                         ));
  1195.                         $orders->setCustomer($customerObj);
  1196.                 }
  1197.                 $orders->setIsActive(1);
  1198.                 $orders->setOrderStatus($orderStatus);
  1199.                 $orders->setCreatedAt(new \DateTime());
  1200.                 $em->persist($orders);
  1201.                 $em->flush();     
  1202.                 if($orders)
  1203.                 {
  1204.                 $orderDetailMail ="<table style='width:100%;text-align: left!important;'>
  1205.                 <tr style='border-bottom:1px solid #ccc'>
  1206.                   <th>Producto</th><th></th>
  1207.                 </tr>";              
  1208.                 $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  1209.                     "productId" => $product_id
  1210.                  ));
  1211.                 $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  1212.                     "offerId" => $offer_id
  1213.                 ));                                
  1214.                 $orderDetail = new OrderDetail();
  1215.                 $orderDetail->setOrder($orders);
  1216.                 $orderDetail->setProduct($productObj);
  1217.                 $orderDetail->setQuantity(1);
  1218.                 $orderDetail->setPriceGiven($price);
  1219.                 $orderDetail->setOriginalPrice($productObj->getMainPrice());                    
  1220.                 $orderDetail->setCreatedAt(new \DateTime());
  1221.                 $orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>                          
  1222.                     <td style='padding:10px;text-align: left!important;'>
  1223.                         <img style='height:80px' src='".$productObj->getMainPicture()."' >
  1224.                     </td>
  1225.                       <td style='padding:10px;text-align: left!important;'>
  1226.                           ".$productObj->getName()."<br>
  1227.                           $symbol.$price x 1 = <b>$symbol.".number_format($price2'.''')."</b><br>                                         
  1228.                   ";
  1229.                 if($offer_id && $offer_id != '')
  1230.                 {
  1231.                     $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  1232.                         "offerId" => $offer_id
  1233.                     ));            
  1234.                     $orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
  1235.                     $orderDetail->setOffer($offerObj);
  1236.                 }
  1237.                 $orderDetailMail.="</td></tr>";
  1238.                 $em->persist($orderDetail);
  1239.                 $em->flush();            
  1240.                 //RESTAMOS DE INVENTARIO
  1241.                 $hasInventory $productObj->getHasInventory();
  1242.                 if($hasInventory == '1')
  1243.                 {
  1244.                     $productInventory $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
  1245.                         "product" => $productObj
  1246.                     ));                                                
  1247.                     if($productInventory)
  1248.                     {
  1249.                         $oldStock $productInventory->getAvailable();
  1250.                         $stock $oldStock 1;
  1251.                         $productInventory->setAvailable($stock);
  1252.                         $em->persist($productInventory);
  1253.                         $em->flush();    
  1254.                         $productInventoryLog = new ProductInventoryLog();
  1255.                         $productInventoryLog->setProduct($productObj);
  1256.                         $productInventoryLog->setCreatedAt(new \DateTime());
  1257.                         $productInventoryLog->setOrderDetail($orderDetail);
  1258.                         $productInventoryLog->setSelledQuantityy(1);
  1259.                         $em->persist($productInventoryLog);
  1260.                         $em->flush();
  1261.                     }
  1262.                 }
  1263.                 $orderDetailMail.="</table>";   
  1264.                 $grandTotal $price;
  1265.                 $orders->setTotalOriginal($grandTotal);
  1266.                 $orders->setTotal(number_format($grandTotal2'.'','));
  1267.                 $orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal2'.'',')." </h3>";
  1268.                 $em->persist($orders);
  1269.                 $em->flush();   
  1270.                 $purchaserValue "";
  1271.                 $emailAnonymous="";
  1272.                 foreach($data as $purchaser)
  1273.                 {
  1274.                         if($purchaser['is_email'] == true){
  1275.                             $emailAnonymous $purchaser['value']; 
  1276.                         }
  1277.                         $fieldClientObj $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
  1278.                             "fieldClientId" => $purchaser['field_client_id']
  1279.                         ));    
  1280.                         $fieldTypeObj $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
  1281.                             "fieldTypeId" => $purchaser['field_type_id']
  1282.                         ));                                
  1283.                         $orderField = new OrderField();
  1284.                         $orderField->setOrder($orders);
  1285.                         $orderField->setFieldClient($fieldClientObj);
  1286.                         $orderField->setFieldType($fieldTypeObj);
  1287.                         $orderField->setName($purchaser['name']);
  1288.                         if($purchaser['field_type_id'] == 3)
  1289.                         {
  1290.                             $fieldValueObj $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
  1291.                                 "fieldValueId" => $purchaser['value']
  1292.                             ));    
  1293.                                 if($fieldValueObj)
  1294.                                 {
  1295.                                     $orderField->setFieldValue($fieldValueObj);                    
  1296.                                 }
  1297.                         } else if($purchaser['field_type_id'] == 4)
  1298.                         {
  1299.                                 $lat $purchaser['value']['lat'];
  1300.                                 $lng $purchaser['value']['lng'];                    
  1301.                                 $orderField->setValueText("$lat,$lng");                    
  1302.                         } else {
  1303.                                 $orderField->setValueText($purchaser['value']);                    
  1304.                         }
  1305.                         $orderField->setCreatedAt(new \DateTime());                
  1306.                         $em->persist($orderField);
  1307.                         $em->flush();                
  1308.                 }        
  1309.                 //ENVÍO DE EMAIL
  1310.                 $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1311.                     "clientId" => $client_id
  1312.                 ));
  1313.                 $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1314.                     "client" => $client
  1315.                 ));        
  1316.                 $MailHelper = new MailHelper();   
  1317.                 $rootWebUrl =  $MailHelper->getRootWebAppURL("0");
  1318.                 $subject 'Nuevo pedido registrado #'.$orders->getOrderId();
  1319.                 $textMessage $setting->getDirectTemplateConfirmationOrders();
  1320.                 $array_cc = array();
  1321.                 $mails_sent "";
  1322.                 if($userData){
  1323.                     $mailTo =  $customerObj->getEmail();  
  1324.                     $mailCopy $setting->getDirectEmailNotificationOrder();
  1325.                     $mails_sent=$mailTo.",".$mailCopy;
  1326.                 }else{
  1327.                     if($emailAnonymous != ''){
  1328.                         $mailTo $emailAnonymous;
  1329.                         $mailCopy $setting->getDirectEmailNotificationOrder();
  1330.                         $mails_sent=$mailTo.",".$mailCopy;
  1331.                     }else{
  1332.                         $mailTo $setting->getDirectEmailNotificationOrder();
  1333.                         $mails_sent=$mailTo;
  1334.                         $mailCopy null;
  1335.                     }
  1336.                 }
  1337.                 
  1338.                 $footer1 =  null;
  1339.                 $textMessage str_replace('_TABLA_PEDIDOS_''<br>'.$orderDetailMail$textMessage);
  1340.                 $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  1341.                     'emailTitle'    =>  $subject,
  1342.                     'message'       =>  $textMessage,
  1343.                     'footer1'       =>  $footer1,                   
  1344.                     'user'          =>  '',
  1345.                     'rootWebUrl'    =>  $rootWebUrl
  1346.                 ) )->getContent();
  1347.                 $MailHelper->sendEmail($client->getName(),$mailTo$subject$myMessage$mailCopy );
  1348.                 //Guardamos log de envío de alerta
  1349.                 $alertPurchase = new AlertPurchase();
  1350.                 $alertPurchase->setClient($client);
  1351.                 $alertPurchase->setCreatedAt(new \DateTime());
  1352.                 $alertPurchase->setEmailSent($mails_sent);
  1353.                 $alertPurchase->setIsActive(1);
  1354.                 $alertPurchase->setOrder($orders);
  1355.                 $em->persist($alertPurchase);
  1356.                 $em->flush();    
  1357.                 return new JsonResponse(array(
  1358.                     'status'  => 'success',
  1359.                     'orderId' => $orders->getOrderId() 
  1360.                 ));
  1361.             
  1362.         } else {
  1363.             
  1364.             return new JsonResponse(array(
  1365.                 'status'  => 'error',
  1366.                 'orderId' => ''
  1367.             ));            
  1368.             
  1369.         }
  1370.         
  1371.         
  1372.         
  1373.     }
  1374.     
  1375.     /**     
  1376.      * @Route("{slug}/checkout/validate-cart", name="frontend_checkout_validate_cart")
  1377.      */
  1378.     public function checkoutValidateCartAction(Request $request$slug)
  1379.     {
  1380.         $currentCart  $this->get("session")->get("cart");
  1381.         $cartList     json_decode($currentCart);
  1382.         if(count($cartList) > 0)
  1383.         {        
  1384.             $validate true;
  1385.             foreach($cartList as $cart)
  1386.             {
  1387.                 $product_stock $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($cart->pid);
  1388.                 $stock 0;
  1389.                 if($product_stock){
  1390.                     if($product_stock['available'] != ''){
  1391.                         $stock $product_stock['available'];
  1392.                     }
  1393.                     
  1394.                     if($product_stock['has_inventory'] != '1'){
  1395.                         $stock 'not_stock';
  1396.                     }
  1397.                 }
  1398.                 if($stock != 'not_stock'){
  1399.                     if($cart->quantity $stock){
  1400.                         $validate false;
  1401.                         break;
  1402.                     }
  1403.                 }
  1404.             }
  1405.             
  1406.         }
  1407.         
  1408.         return new JsonResponse(array(
  1409.             'validate'  => $validate
  1410.         ));    
  1411.                 
  1412.     }
  1413.     
  1414.     /**    
  1415.      * @Route("{slug}/checkout/validate-stock", name="frontend_checkout_validate_stock")
  1416.      */
  1417.     public function checkoutValidateStockAction(Request $request$slug)
  1418.     {
  1419.         $id $request->get('id');
  1420.         if($id != '')
  1421.         {        
  1422.             $validate true;
  1423.          
  1424.             $product_stock $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($id);
  1425.             $stock 0;
  1426.             if($product_stock){
  1427.                 if($product_stock['available'] != ''){
  1428.                     $stock $product_stock['available'];
  1429.                 }
  1430.                 if($product_stock['is_not_stock'] == '1'){
  1431.                     $stock 'not_stock';
  1432.                 }
  1433.             }
  1434.             if($stock != 'not_stock'){
  1435.                 if($stock 1){
  1436.                     $validate false;
  1437.                 }
  1438.             }
  1439.             
  1440.             
  1441.         }
  1442.         
  1443.         return new JsonResponse(array(
  1444.             'validate'  => $validate
  1445.         ));    
  1446.         
  1447.         
  1448.     }
  1449.     
  1450.             
  1451.     /**
  1452.      *
  1453.      * @Route("{slug}/checkout/thanks", name="frontend_checkout_thanks")
  1454.      */
  1455.     public function checkOutThanksAction(Request $request$slugHelperService $helperService)
  1456.     {
  1457.         
  1458.         // replace this example code with whatever you need
  1459.         //$client_id = $this->getParameter('client_id');
  1460.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1461.             "slug" => $slug
  1462.         ));
  1463.         if(!$client)
  1464.         {
  1465.             //Si no se encuentra debe indicar algún error
  1466.         }
  1467.         $orderNumberRaw $request->get('orderNumber','');       
  1468.         $orderNumber    $this->encryptor->decrypt($orderNumberRaw);
  1469.         $order          $this->getDoctrine()->getRepository(\App\Entity\Orders::class)->findOneBy(array("orderId"=> $orderNumber));        
  1470.         
  1471.         if(!$order)
  1472.         {            
  1473.             return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
  1474.         }
  1475.         
  1476.         //$categories   = $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);        
  1477.         $settings       $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1478.             "Client" => $client
  1479.         ));
  1480.         $qrImage $helperService->generateQr($orderNumberRaw);
  1481.     
  1482.         return $this->render('Frontend/Checkout/thanks.html.twig', array(
  1483.             'productCategory' => '',
  1484.             'pager_limit'     => 12,
  1485.             'globalSearch'    => '',
  1486.             'settings'        => $settings,
  1487.             'orderNumber'     => $orderNumber,
  1488.             'brand'           => '',
  1489.             'category'        => '',
  1490.             'slug'            => $slug,
  1491.             'type'            => $order->getOrderType(),
  1492.             'qrImage'         => $qrImage
  1493.         ));
  1494.     }    
  1495.     
  1496.  
  1497.     
  1498.    /**
  1499.      * @Route("{slug}/checkout/payment", name="frontend_checkout_payment")
  1500.      */
  1501.     public function checkoutPaymentAction(Request $request$slug)
  1502.     {
  1503.         $purchaser    $request->get('query');
  1504.         $purchaserObj $purchaser;
  1505.         
  1506.         $currentCart  $this->get("session")->get("cart");
  1507.         $response     $currentCart;
  1508.        
  1509.         return new JsonResponse(array('status' => 'success''data' => $purchaserObj));
  1510.         
  1511.     } 
  1512.     
  1513.     /**
  1514.      * @Route("/checkout/test_payment", name="frontend_checkout_test")
  1515.      */
  1516.     public function checkoutTestPayment(Request $requestPaymentQPayProHelper $paymentQPayProHelper)
  1517.     {
  1518.         $result $this->encryptor->encrypt(927);
  1519.         echo $result;exit;
  1520.         $em $this->getDoctrine()->getManager();
  1521.         /*$parameters = array(
  1522.             "x_amount"        => 1.00,
  1523.             "x_currency_code" => "GTQ",
  1524.             "x_product_id"    => "1618",
  1525.             "x_freight"       => 0,
  1526.             "x_audit_number"  => "123",
  1527.             "x_line_item"     => "T-shirt Live Dreams<|>w01<|><|>1<|>1000.00<|>N",
  1528.             "x_email"         => "servicio@aguilalibreweb.com",
  1529.             "x_fp_sequence"   => "123",
  1530.             "x_fp_timestamp"  => time(),
  1531.             "x_invoice_num"   => "123",
  1532.             "x_first_name"    => "Customer",
  1533.             "x_last_name"     => "Name",
  1534.             "x_company"        => "C/F",
  1535.             "x_address"       => "Guatemala",
  1536.             "x_city"             => "Guatemala",
  1537.             "x_state"         => "Guatemala",
  1538.             "x_country"       => "Guatemala",
  1539.             "x_zip"           => "01056",                 
  1540.             "cc_number"       => "4111111111111111",
  1541.             "cc_exp"          => "01/26",
  1542.             "cc_cvv2"         => "4567",
  1543.             "cc_name"         => "Josue Prueba Dos",                        
  1544.             'finger'          => "",
  1545.             "device_fingerprint_id" => ""
  1546.         );
  1547.         
  1548.         $QPayPro   = new PaymentQPayProHelper();                                                           
  1549.         $response  = $QPayPro->executePaymentOld($em, $parameters);*/
  1550.         return new JsonResponse(array('status' => 'success','msg' => $response));
  1551.     }
  1552.     
  1553.     
  1554.    /**
  1555.      * @Route("{slug}/checkout/payment_no_cash", name="frontend_checkout_no_cash")
  1556.      */
  1557.     public function checkoutPaymentNoCashAction(EntityManagerInterface $entityManagerRequest $requestPaymentNeoNetHelper $paymentNeoNetHelperPaymentQPayProHelper $paymentQPayProHelper$slug)
  1558.     {
  1559.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  1560.         $userData false;
  1561.         if($lastUsername)
  1562.         {
  1563.             $userData $request->getSession()->get($lastUsername);        
  1564.         }
  1565.         
  1566.         $ccData        $request->get('ccData');
  1567.         $purchasers    $request->get('query');
  1568.         $paymentId     $request->get('pmid');
  1569.         $deliveryPrice $request->get('deliveryPrice');
  1570.         $finger        $request->get('finger');
  1571.         $device_fingerprint_id $request->get('device_fingerprint_id');
  1572.         $em $this->getDoctrine()->getManager();
  1573.         //$client_id = $this->getParameter('client_id');
  1574.         $session_uniq_id uniqid();
  1575.                         
  1576.         //Información de la tarjeta
  1577.         $dummyOrderId  date("Ymdhis").rand(1,999);
  1578.         $expDate       $ccData['ccmonth']."/".$ccData['ccyear'];
  1579.         $cleanNumber   str_replace(" """$ccData['ccn']);
  1580.         //Si viene desde la selección de un Token, entonces usaremos el nombre de sesión
  1581.         //Que seguramente debería tener su sesión iniciada para usar la función de tokens
  1582.         if($request->get('paymentMode') == 'token')
  1583.         {
  1584.             $customer_name explode(' ',$userData['name']);
  1585.         } else {
  1586.             $customer_name explode(' ',$ccData['name']);                    
  1587.         }
  1588.         if(count($customer_name) == || !is_array($customer_name))
  1589.         {
  1590.             return new JsonResponse(array(
  1591.                 'status' => 'error',
  1592.                 'msg'    => 'Por favor, escriba su nombre como aparece en la tarjeta de crédito'
  1593.             ));
  1594.         }
  1595.         if($paymentId 0)
  1596.         {
  1597.             
  1598.             $clientObj $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array('slug' => $slug));            
  1599.             if(!$clientObj)
  1600.             {
  1601.                 //Si no encuentra el cliente, entonces da error
  1602.                 return new JsonResponse(array(
  1603.                     'status' => 'error',
  1604.                     'msg'    => 'No se puede realizar la transacción en este momento. Por favor, informar de este error a soporte técnico (A34)'
  1605.                 ));
  1606.             }
  1607.             //Si el customer no esta registrado y no hay un campo configurado para email entonces envia el email al cliente
  1608.             $emailCustomer $clientObj->getEmail();
  1609.             if($userData)
  1610.             {
  1611.                 $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array('customerId' => $userData['customer_id']));    
  1612.                 $emailCustomer $customerObj->getEmail();                        
  1613.             } else {
  1614.                 foreach($purchasers['purchaser'] as $purchaser)
  1615.                 {                        
  1616.                     if($purchaser['is_email'] == true)
  1617.                     {
  1618.                         $emailCustomer $purchaser['value']; 
  1619.                     }
  1620.                 }
  1621.             }
  1622.                     
  1623.             $paymentMethod $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  1624.                 'paymentMethodId' => $paymentId
  1625.                 'Client' => $clientObj
  1626.             ));
  1627.             if($paymentMethod)
  1628.             {
  1629.                 //---- VARIABLES QUE USAN TODOS LOS GATEWAYS -----///
  1630.                 //Calculo de Total incluyendo cargos dPre envio
  1631.                 $cartInfo   $this->refreshCart($slug);
  1632.                 $grandTotal 0;
  1633.                 if($deliveryPrice == 'N')
  1634.                 {
  1635.                     $grandTotal $cartInfo['price'];                        
  1636.                 } else if($deliveryPrice == "FREE")
  1637.                 {
  1638.                     $grandTotal $cartInfo['price'];    
  1639.                 } else {
  1640.                     if($deliveryPrice 0)
  1641.                     {
  1642.                         $grandTotal = ($cartInfo['price']+$deliveryPrice);                      
  1643.                     } else {
  1644.                         $grandTotal $cartInfo['price'];                      
  1645.                     }
  1646.                 }
  1647.                 //Agregando el servife fee
  1648.                 if($clientObj->getServiceFee() > 0)
  1649.                 {
  1650.                     $withServiceFee $grandTotal $clientObj->getServiceFee();                        
  1651.                     $grandTotal     number_format($withServiceFee2'.''');                        
  1652.                 }
  1653.                 //---- FINALIZAN VARIABLES QUE USAN TODOS LOS GATEWAYS -----///
  1654.                 
  1655.                 //QPAY PRO
  1656.                 if($paymentMethod->getPaymentMethodGateway() && $paymentMethod->getPaymentMethodGateway()->getPaymentMethodGatewayId() == '1')
  1657.                 {
  1658.                                                 
  1659.                     $order    false;                    
  1660.                     $QPayPro  = new PaymentQPayProHelper();        
  1661.                     
  1662.                     //Si se usa el metodo para llenar los datos de tarjeta de crédito
  1663.                     if($request->get('paymentMode') == 'card')
  1664.                     {
  1665.                         $parameters = array(
  1666.                             "x_amount"        => $grandTotal,
  1667.                             "x_currency_code" => $clientObj->getCurrency()->getCurrencyIso(),
  1668.                             "x_product_id"    => "1618",
  1669.                             "x_freight"       => 0,
  1670.                             "x_audit_number"  => $dummyOrderId,
  1671.                             "x_line_item"     => $cartInfo['qpay_pro'],
  1672.                             "x_email"         => $emailCustomer,
  1673.     
  1674.                             "x_fp_sequence"   => $dummyOrderId,
  1675.                             "x_fp_timestamp"  => time(),
  1676.                             "x_invoice_num"   => $dummyOrderId,
  1677.                             "x_first_name"    => $customer_name[0],
  1678.                             "x_last_name"     => $customer_name[1],
  1679.                             "x_company"        => "C/F"// Company o C/F
  1680.                             "x_address"       => "Guatemala",
  1681.                             "x_city"             => "Guatemala",
  1682.                             "x_state"         => "Guatemala",
  1683.                             "x_country"       => "Guatemala",
  1684.                             "x_zip"           => "01056",     
  1685.                             
  1686.                             "cc_number"       => $cleanNumber,
  1687.                             "cc_exp"          => $expDate,
  1688.                             "cc_cvv2"         => $ccData['ccv'],
  1689.                             "cc_name"         => $ccData['name'],                        
  1690.     
  1691.                             'finger'          => $finger,
  1692.                             "device_fingerprint_id" => $device_fingerprint_id                                                                                                        
  1693.                         );
  1694.                         $response $QPayPro->executePayment($em$parameters$clientObj$paymentId);
  1695.                     //Si se usa el metodo de pago TOKEN (Solo para usuarios que esten registrados)
  1696.                     } else if($request->get('paymentMode') == 'token')
  1697.                     {
  1698.                         $parameters = array(
  1699.                             "x_amount"   => $grandTotal,
  1700.                             "x_currency" => $clientObj->getCurrency()->getCurrencyIso()
  1701.                         );
  1702.                         $customerTokenDecrypted $this->encryptor->decrypt($request->get('customerToken'));
  1703.                         $tokenObj $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findOneBy(array(
  1704.                             'customerTokenId' => $customerTokenDecrypted,
  1705.                             'is_active' => 1                            
  1706.                         ));
  1707.                         if($tokenObj)
  1708.                         {                            
  1709.                             
  1710.                             $response $QPayPro->useToken($em$parameters$clientObj$paymentId$tokenObj->getToken());
  1711.                         } else {
  1712.                             return new JsonResponse(array(
  1713.                                 'status' => 'error',
  1714.                                 'msg'    => 'No es posible utilizar esta tarjeta guardada en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
  1715.                             ));    
  1716.                         }
  1717.                     } else {
  1718.                         return new JsonResponse(array(
  1719.                             'status' => 'error',
  1720.                             'msg'    => 'No es posible realizar la transacción en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
  1721.                         ));    
  1722.                     }
  1723.                     
  1724.                     
  1725.                     if(isset($response->responseCode))
  1726.                     {
  1727.                                                 
  1728.                         if(strlen($response->responseText[0]) == 1)
  1729.                         {                                            
  1730.                             $text $response->responseText;                                                
  1731.                         } else {                                            
  1732.                             $text $response->responseText[0];                                                                        
  1733.                         }     
  1734.                         
  1735.                         $paymentStatusObj $this->getDoctrine()->getRepository(\App\Entity\PaymentStatus::class)->findOneBy(array(
  1736.                             'paymentStatusId' => 1                                                    
  1737.                         ));
  1738.                         $paymentObj = new Payment();
  1739.                         $paymentObj->setLast4Tdc(substr($cleanNumber,13,16));
  1740.                         $paymentObj->setResult($response->result);
  1741.                         $paymentObj->setTitle($response->title);
  1742.                         $paymentObj->setCustomAuthCode($dummyOrderId);
  1743.                         $paymentObj->setResponseCode($response->responseCode);
  1744.                         $paymentObj->setResponseText($response->responseText);
  1745.                         $paymentObj->setResponseObject(json_encode($response));
  1746.                         $paymentObj->setPaymentMethod($paymentMethod);
  1747.                         $paymentObj->setPaymentStatus($paymentStatusObj);
  1748.                         
  1749.                         if($request->get('paymentMode') == 'token')
  1750.                         {
  1751.                             $paymentObj->setResponseAuthorization($response->responseAutorization);
  1752.                             $paymentObj->setIdTransaction($response->transactionId);
  1753.                         } else {
  1754.                             $paymentObj->setResponseAuthorization($response->responseAuthorization);
  1755.                             $paymentObj->setIdTransaction($response->idTransaction);
  1756.                         }
  1757.                                                 
  1758.                         $paymentObj->setAmount($grandTotal);
  1759.                         //$paymentObj->setRequest(json_encode($parameters));
  1760.                         $paymentObj->setCreatedAt(new \DateTime());
  1761.                         $paymentObj->setClient($clientObj);
  1762.                         $em->persist($paymentObj);
  1763.                         $em->flush(); 
  1764.                         
  1765.                         if($response->responseCode == '100')
  1766.                         {        
  1767.                             return new JsonResponse(array(
  1768.                                 'status' => 'success',
  1769.                                 'data'   => $response,
  1770.                                 'dummyOrderId' => $dummyOrderId,
  1771.                                 'msg' => 'Pago recibido correctamente, estamos procesando en este momento la orden'
  1772.                             ));                                                        
  1773.                         } else {                                                 
  1774.                             return new JsonResponse(array(
  1775.                                 'status' => 'error',
  1776.                                 'data'   => $response,
  1777.                                 'dummyOrderId' => $dummyOrderId,
  1778.                                 'msg' => $text
  1779.                             ));                                    
  1780.                         }    
  1781.                         
  1782.                     }        
  1783.                 //Termina qpay_pro
  1784.                 }
  1785.                 //Inicio de NEO_NET
  1786.                 if($paymentMethod->getPaymentMethodGateway() && $paymentMethod->getPaymentMethodGateway()->getPaymentMethodGatewayId() == '2')
  1787.                 {
  1788.                     if($request->get('paymentMode') == 'card')
  1789.                     {
  1790.                                      
  1791.                         
  1792.                         $cardType $paymentNeoNetHelper->getCardType($cleanNumber);
  1793.                         $parameters = [
  1794.                             "cc_number"         => $cleanNumber,
  1795.                             "x_exp_month"     => $ccData['ccmonth'],
  1796.                             "x_exp_year"      => $ccData['ccyear'],
  1797.                             "x_card_type"     => $cardType,
  1798.                             "cc_cvv2"         => $ccData['ccv']
  1799.                         ];
  1800.                                         
  1801.                         $shopperIp $paymentNeoNetHelper->getClientIP();                        
  1802.                 
  1803.                         $response $paymentNeoNetHelper->authorizePayment($entityManager$clientObj->getClientId(), $paymentId$grandTotal$parameters$dummyOrderId$shopperIp);
  1804.                         
  1805.                         if(isset($response->PrivateUse63))
  1806.                         {
  1807.                             if(isset($response->PrivateUse63->AlternateHostResponse22) && $response->PrivateUse63->AlternateHostResponse22 == 'APROBADA')
  1808.                             {
  1809.                                 $paymentStatusObj $this->getDoctrine()->getRepository(\App\Entity\PaymentStatus::class)->findOneBy(array(
  1810.                                     'paymentStatusId' => 1                                                    
  1811.                                 ));
  1812.         
  1813.                                 $paymentObj = new Payment();
  1814.                                 $paymentObj->setLast4Tdc(substr($cleanNumber,13,16));
  1815.                                 $paymentObj->setResult($response->ProcessingCode);
  1816.                                 $paymentObj->setTitle($response->PrivateUse63->AlternateHostResponse22);
  1817.                                 $paymentObj->setCustomAuthCode($dummyOrderId);
  1818.                                 $paymentObj->setResponseCode($response->ResponseCode);
  1819.                                 $paymentObj->setResponseText($response->SystemsTraceNo);
  1820.                                 $paymentObj->setResponseObject(json_encode($response));
  1821.                                 $paymentObj->setPaymentMethod($paymentMethod);
  1822.                                 $paymentObj->setPaymentStatus($paymentStatusObj);
  1823.                                 
  1824.                                 if($request->get('paymentMode') == 'token')
  1825.                                 {
  1826.                                     $paymentObj->setResponseAuthorization($response->SystemsTraceNo);
  1827.                                     $paymentObj->setIdTransaction($response->AuthIdResponse);
  1828.                                 } else {
  1829.                                     $paymentObj->setResponseAuthorization($response->SystemsTraceNo);
  1830.                                     $paymentObj->setIdTransaction($response->AuthIdResponse);
  1831.                                 }
  1832.                                                         
  1833.                                 $paymentObj->setAmount($grandTotal);
  1834.                                 $paymentObj->setRequest(json_encode($parameters));
  1835.                                 $paymentObj->setCreatedAt(new \DateTime());
  1836.                                 $paymentObj->setClient($clientObj);
  1837.                                 $em->persist($paymentObj);
  1838.                                 $em->flush(); 
  1839.                                 return new JsonResponse(array(
  1840.                                     'status' => 'success',
  1841.                                     'data'   => $response,
  1842.                                     'dummyOrderId' => $dummyOrderId,
  1843.                                     'msg' => 'Pago recibido correctamente, estamos procesando en este momento la orden'
  1844.                                 ));                                                                                        
  1845.                             }
  1846.                         }
  1847.                 
  1848.                         $text "No se pudo procesar el pedido en este momento, si el problema persiste contacta a servicio al cliente";
  1849.                         return new JsonResponse(array(
  1850.                             'status' => 'error',
  1851.                             'data'   => $response,
  1852.                             'dummyOrderId' => $dummyOrderId,
  1853.                             'msg'    => $text
  1854.                         ));                                                    
  1855.                     }
  1856.                 }
  1857.                         
  1858.                         
  1859.                         
  1860.             }
  1861.             
  1862.         }
  1863.        
  1864.         return new JsonResponse(array(
  1865.             'status' => 'error',
  1866.             'msg'    => 'No fue posible comunicarse con la pasarela de Pago. Por favor utilice otro método de pago para continuar'
  1867.         ));
  1868.         
  1869.     }        
  1870.    
  1871.         
  1872.     
  1873.     
  1874.     /**
  1875.      *
  1876.      * @Route("{slug}/checkout_fields", name="frontend_checkout_fields")
  1877.      */
  1878.     public function checkoutFieldsAction(Request $request$slug)
  1879.     {
  1880.         //$clientIdNum = $this->getParameter('client_id');
  1881.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1882.             "slug" => $slug
  1883.         ));
  1884.         $clientIdNum $client->getClientId();
  1885.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  1886.         $userData false;
  1887.         if($lastUsername)
  1888.         {
  1889.             $userData $request->getSession()->get($lastUsername);        
  1890.         }
  1891.         
  1892.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1893.             "Client" => $client
  1894.         ));
  1895.         
  1896.         //VERIFICAMOS HORARIOS
  1897.         $store_status   'open';                
  1898.         $message_closed "";
  1899.         $day_number     date('N');
  1900.         
  1901.         $hoursToday $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$clientIdNum);
  1902.         if($hoursToday['is_open'] == '0')
  1903.         {
  1904.             $store_status    'closed';                    
  1905.             $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1906.                 "clientId" => $clientIdNum
  1907.             ));
  1908.             $message_closed  $information->getClosedNotice();
  1909.         }
  1910.         
  1911.         $type "";
  1912.         
  1913.         if($request->get('direct_field_id'))
  1914.         {
  1915.             # REEMPLAZO DE TIENDA CERRADA
  1916.             //Si tiene un horario configurado para este dia, entonces se reemplaza
  1917.             if($store_status == 'open')
  1918.             {
  1919.                 $cartField    $request->get('direct_field_id');
  1920.             }else{
  1921.                 $cartField       $settings->getClosedDirectFieldList()->getFieldListId();
  1922.             }
  1923.             $type"direct";
  1924.         } else {
  1925.             # REEMPLAZO DE TIENDA CERRADA
  1926.             //Si tiene un horario configurado para este dia, entonces se reemplaza
  1927.             //obtenemos el día actual
  1928.             if($store_status == 'open')
  1929.             {
  1930.                 $cartField $settings->getCartFieldList()->getFieldListId();
  1931.             } else {
  1932.                 $cartField $settings->getClosedCartFieldList()->getFieldListId();                            
  1933.             }
  1934.             $type="cart";
  1935.         }                
  1936.                 
  1937.         if(true)
  1938.         {
  1939.                 $array $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById($cartField,$clientIdNum);
  1940.         } else {
  1941.                 //Si no tiene campos el formulario que deberia de ser, mandamos el formulario por defecto.
  1942.                 $array $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById(0,$clientIdNum);
  1943.         }
  1944.         
  1945.         $finalArray = array();
  1946.         
  1947.         
  1948.         foreach($array as $item)
  1949.         {
  1950.                         
  1951.             $merged $item;                        
  1952.             
  1953.             if($item['field_type_id'] == 4)
  1954.             {
  1955.                 $polygons $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getPolygonsForFieldClient($item['field_client_id']);
  1956.                 if($polygons)
  1957.                 {
  1958.                     $polArray = array();
  1959.                     foreach($polygons as $pols)
  1960.                     {
  1961.                         $polArray[] = $pols;
  1962.                     }
  1963.                     $merged array_merge($item, array('polygons'=>$polArray));
  1964.                 
  1965.                 }
  1966.             }
  1967.             
  1968.             $finalArray[] = $merged;            
  1969.             
  1970.         }
  1971.                
  1972.         /*echo "<pre>";
  1973.           print_r($merged);
  1974.         echo "</pre>";    */    
  1975.         
  1976.         /*return new JsonResponse(array(
  1977.             'status'   => 'success',
  1978.             'result'   => $array,
  1979.             'store_status'  => $store_status
  1980.         ));*/
  1981.         $customerLocation '';
  1982.         if($userData)
  1983.         {
  1984.             if($userData['customer_id'])
  1985.             {
  1986.                 $customerLocation $this->getDoctrine()->getRepository(\App\Entity\CustomerLocation::class)->findOneBy([
  1987.                     "Customer" => $userData['customer_id']
  1988.                 ]);
  1989.             }
  1990.         }
  1991.         $storeList $this->getDoctrine()->getRepository(\App\Entity\Store::class)->findBy([
  1992.             'Client'    => $clientIdNum,
  1993.             'is_active' => 1                
  1994.         ]); 
  1995.                 
  1996.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1997.             "Client" => $clientIdNum
  1998.         ));
  1999.         return $this->render('Frontend/Checkout/checkout_fields.html.twig', array(
  2000.             'status'           => 'success',
  2001.             'result'           => $finalArray,
  2002.             'slug'             => $slug,
  2003.             'userData'         => $userData,
  2004.             'store_status'     => $store_status,
  2005.             'message_closed'   => $message_closed,
  2006.             'customerLocation' => $customerLocation,
  2007.             'type'             => $type,
  2008.             'storeList'        => $storeList,
  2009.             'settings'         => $settings
  2010.         ));               
  2011.        
  2012.        
  2013.     }    
  2014.     
  2015.     
  2016.     /**
  2017.      *
  2018.      * @Route("{slug}/checkout_table", name="frontend_checkout_table")
  2019.      */
  2020.     public function checkoutTableAction(Request $request$slug)
  2021.     {
  2022.         
  2023.         $cart       json_decode($this->get("session")->get("cart"));
  2024.         $cartArray  = array();
  2025.         $grandTotal 0;
  2026.                 
  2027.         $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  2028.             "slug" => $slug
  2029.         ]);                
  2030.         $client_id $information->getClientId();
  2031.         //Obtenemos simbolo de moneda a utilizar
  2032.         $symbol $information->getCurrency()->getCurrencySymbol();
  2033.         if(count($cart) > 0)
  2034.         {
  2035.             foreach($cart as $item)
  2036.             {
  2037.                 
  2038.                 $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  2039.                     'productId' => $item->pid
  2040.                 ));            
  2041.                 
  2042.                 $productInventory $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($item->pid);
  2043.                 $stock 0;
  2044.                 if($productInventory){
  2045.                     if($productInventory['available'] != ''){
  2046.                         $stock $productInventory['available'];
  2047.                     }
  2048.                     
  2049.                     if($productInventory['has_inventory'] <> 1)
  2050.                     {
  2051.                         $stock 'not_stock';
  2052.                     }
  2053.                     
  2054.                 }
  2055.                 $cleanPrice preg_replace("/[^0-9.]/","",$item->price);                                
  2056.                 $cleanPrice ltrim($cleanPrice,".");
  2057.                 $cleanPrice sprintf('%0.2f',$cleanPrice); 
  2058.                 
  2059.                 $subtotal = ($item->quantity $cleanPrice);
  2060.                 
  2061.                 
  2062.                 $itemArray = [
  2063.                     'product' => [
  2064.                         "name"        => $item->name,
  2065.                         "product_id"  => $item->pid,
  2066.                         "offer_name"  => $item->o_name,
  2067.                         "offer_id"    => $item->oid,
  2068.                         "clean_price" => $cleanPrice,    
  2069.                         "stock"       => $stock,
  2070.                         'subtotal'    => number_format($subtotal2'.'','),
  2071.                         'image'       => $productObj->getMainPicture(),        
  2072.                     ],
  2073.                     "quantity"    => $item->quantity,
  2074.                     "symbol"      => $symbol,
  2075.                     'service_fee' => $information->getServiceFee()
  2076.                 ];
  2077.                 
  2078.                 $grandTotal += $subtotal;                
  2079.                 $cartArray[] = $itemArray;
  2080.                                 
  2081.             }
  2082.         }
  2083.         
  2084.         
  2085.                 
  2086.         $coupon '';
  2087.         $grandTotalFinal $grandTotal;
  2088.         $discount 0;
  2089.         if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
  2090.         {
  2091.             $coupon_id $this->get("session")->get("coupon");
  2092.             $coupon $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
  2093.                 'couponId' => $coupon_id
  2094.             ));    
  2095.             
  2096.             $discount_percent $coupon->getDiscountPercent();
  2097.             $discount         = ($grandTotal*$discount_percent)/100;
  2098.             $grandTotalFinal  $grandTotal $discount;
  2099.         }
  2100.         //SE APLICA EL SERVICE FEE
  2101.         if($information->getServiceFee() && $information->getServiceFee() > 0)
  2102.         {            
  2103.             $grandTotalFinal $grandTotalFinal $information->getServiceFee();
  2104.         }
  2105.         return $this->render('Frontend/Checkout/checkout_table.html.twig', array(
  2106.             'productCategory' => '',
  2107.             'pager_limit'     => 12,
  2108.             'globalSearch'    => '',
  2109.             'slug'            => $slug,
  2110.             'cart'            => $cartArray,
  2111.             'coupon'          => $coupon,
  2112.             'subTotal'        => number_format($grandTotal2'.'','),
  2113.             'discount'        => number_format($discount2'.'','),
  2114.             'grandTotal'      => number_format($grandTotalFinal2'.'','),
  2115.             'symbol'          => $symbol,
  2116.             'service_fee'     => $information->getServiceFee()
  2117.         ));
  2118.     }    
  2119.     /**     
  2120.      * @Route("{slug}/checkout_refresh_cart", name="frontend_checkout_refresh_cart")
  2121.      */
  2122.     public function checkoutRefreshCartAction(Request $request$slug) {
  2123.            
  2124.            
  2125.             $response $this->refreshCart($slug);
  2126.             return new JsonResponse($response);
  2127.     }   
  2128.     
  2129.     
  2130.     public function refreshCart($slug)
  2131.     {
  2132.             
  2133.             $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  2134.                 "slug" => $slug
  2135.             ));        
  2136.             if(!$information)
  2137.             {
  2138.                 //@TODO hacer algo si no se detecta
  2139.             }
  2140.             $client_id $information->getClientId();
  2141.             //Obtenemos simbolo de moneda a utilizar
  2142.             $symbol $information->getCurrency()->getCurrencySymbol();
  2143.             $currentCart json_decode($this->get("session")->get("cart"));
  2144.             if(is_array($currentCart))
  2145.             {
  2146.                 if (count($currentCart) == 0) {
  2147.                     $currentCart = array();
  2148.                 }
  2149.             }
  2150.             
  2151.             $val 0;
  2152.             $priceVal 0;
  2153.             if (is_array($currentCart)) {
  2154.                 $currentCarts $currentCart;
  2155.             } else {
  2156.                 $currentCarts json_decode($currentCart);
  2157.             }
  2158.             //Cadena para gateway de pago
  2159.             $QPayPro "";
  2160.             
  2161.             
  2162.             //-------------------------
  2163.             
  2164.             if(is_array($currentCarts))
  2165.             {
  2166.                 foreach($currentCarts as $cartTemp)
  2167.                 {
  2168.                     $val += $cartTemp->quantity;
  2169.                     $priceVal += $cartTemp->price $cartTemp->quantity;
  2170.                     
  2171.                     //Cadenas para gateway de pago
  2172.                     $QPayPro .= $cartTemp->name."<|>".$cartTemp->pid."<|>".$cartTemp->quantity."<|>".$cartTemp->price."<|>N";
  2173.                 }
  2174.             }
  2175.             
  2176.             $coupon '';
  2177.             $grandTotalFinal $priceVal;
  2178.             $discount 0;
  2179.             if($grandTotalFinal ){
  2180.                 if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
  2181.                     $coupon_id $this->get("session")->get("coupon");
  2182.                     $coupon $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
  2183.                             'couponId' => $coupon_id
  2184.                     ));    
  2185.                     $discount_percent $coupon->getDiscountPercent();
  2186.                     $discount = ($priceVal*$discount_percent)/100;
  2187.                     $grandTotalFinal $priceVal $discount;
  2188.                     $grandTotalFinalnumber_format($grandTotalFinal2'.'',');
  2189.                 }
  2190.             }else{
  2191.                 $grandTotalFinal '';
  2192.             }
  2193.             
  2194.             $url $this->generateUrl('frontend_checkout', ['slug' => $slug]);
  2195.             $html "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
  2196.                 <i class='zmdi zmdi-shopping-cart'></i>$symbol$grandTotalFinal
  2197.                 <small class='cart_bottom_legend'>Clic aquí para terminar</small>
  2198.             </div>";
  2199.             $response = array(
  2200.                 'quantity' => $val,
  2201.                 'price'    => $grandTotalFinal,
  2202.                 'cart'     => $currentCarts,
  2203.                 'html'     => $html,
  2204.                 'qpay_pro' => $QPayPro
  2205.             );    
  2206.             
  2207.             return $response;    
  2208.     }
  2209.     
  2210.     
  2211.     
  2212.     /**
  2213.      * @Route("{slug}/checkout/verify-coupon", name="frontend_checkout_verify_coupon")
  2214.      */
  2215.     public function checkoutVerifyCouponAction(Request $request$slug)
  2216.     {
  2217.         $userData $this->get("session")->get("userData");
  2218.         
  2219.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  2220.             "slug" => $slug
  2221.         ));    
  2222.         $client_id $client->getClientId();
  2223.         if(!$client)
  2224.         {
  2225.             return new JsonResponse(array(
  2226.                 'status'    =>  'error',
  2227.                 'isValid'   =>  0,
  2228.                 'msg'       =>  "No se puede validar el cupón en este momento",
  2229.                 'coupon'    =>  ""
  2230.             ));
  2231.         }
  2232.         $setting  $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  2233.             "Client" => $client
  2234.         ));        
  2235.         $customerId '';
  2236.         if($userData)
  2237.         {
  2238.             $customerId $userData['customer_id'];
  2239.         }
  2240.         $coupon    $request->get('coupon');        
  2241.         
  2242.         //VERIFICAMOS EXISTENCIA DEL CUPÓN
  2243.         $couponExist $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->verifyCoupon($coupon,$customerId$client_id);
  2244.         $isValid false;        
  2245.         $msg     "El cupón no es valido";
  2246.         $this->get("session")->set("coupon"'');
  2247.         if($couponExist)
  2248.         {
  2249.             if($userData)
  2250.             {
  2251.                  if($couponExist['customer_id'] != '' && $couponExist['customer_id'] != $userData['customer_id'])
  2252.                  {
  2253.                     $isValid false;
  2254.                     $msg     "El cupón ingresado no es válido";
  2255.                  }else{                  
  2256.                     $isValid true;
  2257.                  }
  2258.                      
  2259.             }else{
  2260.                 if($couponExist['customer_id'] == '')
  2261.                 {                    
  2262.                     $isValid true;                    
  2263.                 }
  2264.             }
  2265.             
  2266.             //Verificamos productos ofertados 
  2267.             if($isValid && $setting->getCartAllowCouponWhithOffers() == '0')
  2268.             {
  2269.                 $currentCart  $this->get("session")->get("cart");
  2270.                 $cartList     json_decode($currentCart);
  2271.                 if(count($cartList) > 0)
  2272.                 {        
  2273.                    
  2274.                     foreach($cartList as $cart)
  2275.                     {
  2276.                        if($cart->oid != ''){
  2277.                            $isValid false;
  2278.                            $msg     "No es posible utilizar el cúpon con productos ofertados";
  2279.                            break;
  2280.                        }
  2281.                     }
  2282.                 }
  2283.                 
  2284.             }
  2285.             
  2286.             if($isValid){
  2287.                 $this->get("session")->set("coupon"$couponExist['coupon_id']);
  2288.             }
  2289.         }
  2290.         
  2291.         return new JsonResponse(array(
  2292.             'status'    =>  'success',
  2293.             'isValid'   =>  $isValid,
  2294.             'msg'       =>  $msg,
  2295.             'coupon'    =>  $this->get("session")->get("coupon")
  2296.         ));
  2297.         
  2298.     }  
  2299.     
  2300.     
  2301.     /**
  2302.      * @Route("{slug}/checkout/distance-info", name="frontend_checkout_distance_info")
  2303.      */
  2304.     public function distanceInfoAction(Request $requestDistanceHelper $distanceHelper$slug)
  2305.     {
  2306.         
  2307.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  2308.             "slug" => $slug
  2309.         ));        
  2310.         $client_id $client->getClientId();
  2311.         $variable  $this->getDoctrine()->getRepository(\App\Entity\DeliveryVariable::class)->findOneBy(array(
  2312.             "Client" => $client_id
  2313.         ));        
  2314.         
  2315.          $response "";
  2316.          if($variable)
  2317.          {       
  2318.              
  2319.             $latTo $request->get('latTo');
  2320.             $lngTo $request->get('lngTo');             
  2321.             if($latTo != "" && $lngTo != "")
  2322.             {
  2323.                 $dummyLat $variable->getOriginLat();
  2324.                 $dummyLng $variable->getOriginLng();
  2325.                 $distanceHelper = new DistanceHelper();            
  2326.                 $response $distanceHelper->getDistanceInfo($dummyLat$dummyLng$latTo$lngTo$variable->getUseGoogle(), $variable->getApiKey());        
  2327.                 if($response)
  2328.                 {
  2329.                     if(strlen($response['distance']) > 0)
  2330.                     {
  2331.                         $rangeFound  $this->getDoctrine()->getRepository(\App\Entity\DeliveryRange::class)->findRangePrice($response['distance'], $client_id);
  2332.                         if($rangeFound)
  2333.                         {
  2334.                             
  2335.                             if($rangeFound['is_free'] == 1)
  2336.                             {
  2337.                                 $finalPrice 'FREE';        
  2338.                             } else {
  2339.                                 $finalPrice $rangeFound['price'];                        
  2340.                             }
  2341.                             
  2342.                             return new JsonResponse(array(
  2343.                                 'status'         => 'success',
  2344.                                 'delivery_price' => $finalPrice,
  2345.                                 'data'           => $response
  2346.                             ));
  2347.         
  2348.                         }
  2349.                     }
  2350.                 
  2351.                 }
  2352.                 return new JsonResponse(array(
  2353.                     'status'         => 'error',
  2354.                     'delivery_price' => '',
  2355.                     'data'           => $response
  2356.                 ));
  2357.             }
  2358.             
  2359.         } 
  2360.         
  2361.         
  2362.         return new JsonResponse(array(
  2363.             'status'         => 'success',
  2364.             'delivery_price' => '',
  2365.             'data'           => ''
  2366.         ));
  2367.             
  2368.         
  2369.     }  
  2370.     
  2371.         
  2372.       
  2373.     /**
  2374.      * @Route("/checkout/quit-coupon", name="frontend_checkout_quit_coupon")
  2375.      */
  2376.     public function checkoutQuitCouponAction(Request $request)
  2377.     {
  2378.         $this->get("session")->set("coupon",'');
  2379.         return new JsonResponse(array(
  2380.             'status'    => 'success'
  2381.         ));
  2382.         
  2383.     }  
  2384.     
  2385.       
  2386.     /**
  2387.      * @Route("/{slug}", name="frontend_index", requirements={"slug"="^(?!(login|backend|logout|ws)(/|$)).*"}))
  2388.      */
  2389.     public function indexAction(Request $request$slug)
  2390.     {
  2391.         
  2392.         $em        $this->getDoctrine()->getManager();
  2393.         //$client_id = $this->getParameter('client_id');
  2394.         
  2395.         $productCategory "";
  2396.         $pager_limit     12;
  2397.         $globalSearch    "";
  2398.         //$client = $this->getDoctrine()->getRepository(Client::class)->findBy(array("clientId" => $client_id));
  2399.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
  2400.         if(!$client)
  2401.         {
  2402.             return $this->redirectToRoute("homepage_website");
  2403.         }
  2404.         $client_id $client->getClientId();
  2405.         $slides $this->getDoctrine()->getRepository(WebSlide::class)->findBy(array("Client" => $client"is_active" => 1));
  2406.         $webSetting $this->getDoctrine()->getRepository(WebSetting::class)->findOneBy(array("Client" => $client));        
  2407.         
  2408.         $brands        $em->getRepository(Brand::class)->getBrands($client_id);
  2409.         $categories    $em->getRepository(Category::class)->getCategories($client_id);
  2410.         $subcategories $em->getRepository(Subcategory::class)->findBy(array('is_active' => 1'Client'=> $client));
  2411.         $blogs            $em->getRepository(Blog::class)->findBy(array('is_active' => 1'is_published' => 1'featured'=> 1'Client' => $client));
  2412.         
  2413.         // replace this example code with whatever you need
  2414.         return $this->render('Frontend/Index/index.html.twig', array(
  2415.             'productCategory' => $productCategory,
  2416.             'pager_limit'     => $pager_limit,
  2417.             'globalSearch'    => $globalSearch,
  2418.             'slides'          => $slides,
  2419.             'categories'      => $categories,
  2420.             'brands'          => $brands,
  2421.             'blogs'           => $blogs,
  2422.             'slug'            => $slug,
  2423.             'subcategories'   => $subcategories,
  2424.             'webSetting'      => $webSetting,
  2425.             'brand'           => '',
  2426.             'category'        => ''
  2427.         ));
  2428.         
  2429.     }    
  2430.          
  2431. }