src/Controller/PaiementController.php line 1039

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\SessionService;
  4. use App\Service\CartService;
  5. use App\Service\VoucherService;
  6. use App\Entity\Main\CartSession;
  7. use App\Entity\Main\History;
  8. use App\Entity\Main\Reservation;
  9. use App\Entity\Main\ReservationDetails;
  10. use App\Entity\Main\Activity;
  11. use App\Entity\Main\BookedActivity;
  12. use App\Entity\Main\BookedActivityOptions;
  13. use App\Entity\Customer\Customer;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\Mailer\MailerInterface;
  22. use Symfony\Component\Mime\Email;
  23. class PaiementController extends AbstractController
  24. {
  25.     private $ss;
  26.     private $cart_service;
  27.     private $vs;
  28.     private $user_id_boutique;
  29.     private $paiement_mode 'prod';
  30.     private $secretkey = array(
  31.         'prod' => 'sk_live_BWyADRY2i1WkCeCFSdTPB',
  32.         'test' => 'sk_test_3WPuDRaCf7EkPpwK5kLvFq',
  33.     ); 
  34.     public function __construct(SessionService $ssCartService $cart_serviceVoucherService $vs)
  35.     {
  36.         $this->ss $ss;
  37.         $this->cart_service $cart_service;
  38.         $this->vs $vs;
  39.         $this->user_id_boutique '1367';
  40.     }
  41.     /**
  42.      * @Route("/paiement", name="payment")
  43.      */
  44.     public function showRecap(Request $request): Response
  45.     {
  46.         $em $this->getDoctrine()->getManager();
  47.         $cart $this->ss->get();
  48.         $cart_details $this->cart_service->getCartDetails($cart);
  49.         
  50.         // TO-DO faire un service pour savoir le l'environement [dev OU prod]
  51.         // $this->paiement_mode = ($this->getParameter('kernel.environment') == "dev") ? 'test' : 'prod';
  52.         if(empty($cart_details)) {
  53.             return $this->redirectToRoute('home');
  54.         } elseif($this->container->get('security.token_storage')->getToken() != null) {
  55.             $user $this->container->get('security.token_storage')->getToken()->getUser();
  56.         } else {
  57.             return $this->redirectToRoute('customer_login',array('back' => '/paiement'));
  58.         }
  59.         // dd($this->sanitize_cart_details($cart_details));
  60.         $now = new \DateTime('now');
  61.         $cartSession $em->getRepository(CartSession::class)->findOneBy(['id_cart_session' => $user->getId().'_'.$now->format('Ymd')]);
  62.         if(!$cartSession) {
  63.             $cartSession = new CartSession();
  64.         }
  65.         $cartSession->setIdCartSession($user->getId().'_'.$now->format('Ymd'));
  66.         $cartSession->setIdCustomer($user->getId());
  67.         $cartSession->setCartRaw(serialize(array(
  68.             'cart' => $cart,
  69.             'cart_details' => $this->sanitize_cart_details($cart_details
  70.         )));
  71.         $cartSession->setUserAgent($_SERVER['HTTP_USER_AGENT']);
  72.         $cartSession->setDateAdd($now);
  73.         $em->persist($cartSession);
  74.         $em->flush();
  75.         return $this->render('etapes/paiement.html.twig', [
  76.             'temp' => $this->secretkey[$this->paiement_mode],
  77.             'cart' => $cart,
  78.             'cart_details' => $cart_details,
  79.             'controller_name' => 'PaiementController',
  80.             'page_name' => 'page_paiement',
  81.         ]);
  82.     }
  83.     
  84.     private function createReservation($action_paiement$infos$json_total_a_payer$json_total_panier)
  85.     {
  86.         /* POST Method */
  87.         // $data = json_decode($request->request->get('data'));
  88.         $data "";
  89.         $error false;
  90.         // if(md5($this->pk) != $request->request->get('key')) exit();
  91.         
  92.         $customer $this->container->get('security.token_storage')->getToken()->getUser();
  93.         $cart $this->ss->get();
  94.         $cart_details $this->cart_service->getCartDetails($cart);
  95.         $date_arrive = new \DateTime($this->cart_service->getDateArrive($cart));
  96.         $cm $this->getDoctrine()->getManager('customer');
  97.         $em $this->getDoctrine()->getManager();
  98.         $reservation = new Reservation();
  99.         // dd($cart_details);
  100.         // On récupère les infos du client
  101.         // $customer = $em->getRepository(Customer::Class)->findOneBy(['customerNumber' => $customer->getCustomerNumber()]);
  102.         if($customer instanceof Customer)
  103.         {
  104.             $reservation->setCustomerId($customer->getId());
  105.             $reservation->setCustomerNumber($customer->getCustomerNumber());
  106.             $reservation->setFirstname($customer->getFirstname());
  107.             $reservation->setLastname($customer->getLastname());
  108.             $reservation->setCompany($customer->getCompany());
  109.             $reservation->setEmail($customer->getEmail());
  110.             $reservation->setPhone($customer->getPhone());
  111.             $reservation->setPhoneMobile($customer->getPhoneMobile());
  112.             
  113.             $billingAddress "";
  114.             if ($customer->getAddress1() != "" && $customer->getAddress1() != null$billingAddress .= $customer->getAddress1() . "\n";
  115.             if ($customer->getAddress2() != "" && $customer->getAddress2() != null$billingAddress .= $customer->getAddress2() . "\n";
  116.             if ($customer->getPostcode() != "" && $customer->getPostcode() != null$billingAddress .= $customer->getPostcode() . " ";
  117.             if ($customer->getCity() != "" && $customer->getCity() != null$billingAddress .= $customer->getCity();            
  118.             $reservation->setBillingAddress($billingAddress);
  119.         }
  120.         /************************************************/  
  121.         // Extraction des données du panier
  122.         /************************************************/  
  123.         $formulesArray = array();
  124.         $formulesString '';
  125.         $forfaits = array();
  126.         // $forfaitsIdArray = array();
  127.         $tarifs = array();
  128.         $montant_total_ttc 0;
  129.         $montant_total_tva 0;
  130.         $temp_tva_ttcArray = array(); 
  131.         foreach ($cart_details as $key_a => $formule) {
  132.             if($formulesString != ""$formulesString .= ', ';
  133.             $formulesArray[] = $formule['obj_formule']->getCode();
  134.             $formulesString .= $formule['obj_formule']->getCode();
  135.             foreach ($formule['forfaits'] as $key_b => $forfait) {
  136.                 $montant_forfait_ttc 0;
  137.                 $montant_forfait_tva 0;
  138.                 $forfait_tva_ttcArray = array();
  139.                 $forfaits[] = $forfait['obj_forfait'];
  140.                 // $forfaitsIdArray[] = $forfait['obj_forfait']->getId();
  141.                 foreach ($forfait['tarifs'] as $key => $tarif) {
  142.                     $montant_total_ttc += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
  143.                     if(!isset($temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()])) {
  144.                         $temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] = 0;
  145.                     }
  146.                     $temp_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
  147.                     $montant_forfait_ttc += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
  148.                     if(!isset($forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()])) {
  149.                         $forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] = 0;
  150.                     }
  151.                     $forfait_tva_ttcArray[(string) $tarif['obj_tarif']->getTauxTva()] += $tarif['obj_tarif']->getPriceTtc() * (int) $tarif['qty'];
  152.                 }
  153.                 foreach ($forfait['options'] as $key => $option) {
  154.                     $montant_total_ttc += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
  155.                     if(!isset($temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()])) {
  156.                         $temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] = 0;
  157.                     }
  158.                     $temp_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
  159.                     
  160.                     $montant_forfait_ttc += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
  161.                     if(!isset($forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()])) {
  162.                         $forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] = 0;
  163.                     }
  164.                     $forfait_tva_ttcArray[(string) $option['obj_option']->getTauxTva()] += $option['obj_option']->getPriceTtc() * (int) $option['qty'];
  165.                 }
  166.                 foreach ($forfait_tva_ttcArray as $tva => $montant_ttc) {
  167.                     $taux + (float) $tva;
  168.                     $montant_forfait_tva += $montant_ttc $montant_ttc/$taux;
  169.                 }
  170.                 $cart_details[$key_a]['forfaits'][$key_b]['total_ttc'] = $montant_forfait_ttc;
  171.                 $cart_details[$key_a]['forfaits'][$key_b]['total_tva'] = $montant_forfait_tva;
  172.             }
  173.         }
  174.         foreach ($temp_tva_ttcArray as $tva => $montant_ttc) {
  175.             $taux + (float) $tva;
  176.             $temp_montant_tva $montant_ttc $montant_ttc/$taux;
  177.             if(isset($cart['code_promo'])) {
  178.                 $temp_montant_tva $temp_montant_tva - ($temp_montant_tva $cart['code_promo']->getPercent());
  179.             }
  180.             $montant_total_tva += $temp_montant_tva;
  181.         }
  182.         // $cart['code_promo']->getPercent()
  183.         
  184.         if(isset($cart['bon_numerique'])) {
  185.             foreach ($cart['bon_numerique'] as $key => $bon) {
  186.                 // $bonDetails = new ReservationDetails();
  187.                 // $bonDetails->setDesignation('Bon numérique : '.$bon['bon'].' ('.$bon['total'].')');
  188.                 // $bonDetails->setDate($date_arrive);
  189.                 // $bonDetails->setReservation($reservation);
  190.                 // $bonDetails->setTotalTTC(round(0 - $bon['total']),2);
  191.                 // $em->persist($bonDetails);
  192.                 // $em->flush();
  193.                 $montant_total_ttc $montant_total_ttc $bon['total'];
  194.                 $montant_total_tva $montant_total_ttc - ($montant_total_ttc 1.2 );
  195.             }
  196.         }
  197.         if(isset($cart['code_promo'])) {
  198.             if($cart['code_promo']->getTypeReduction() == 'percentage') {
  199.                 // $montant_total_tva = $montant_total_tva - ($montant_total_tva * $cart['code_promo']->getPercent() );
  200.                 $montant_total_ttc $montant_total_ttc - ($montant_total_ttc $cart['code_promo']->getPercent() );
  201.             } elseif($cart['code_promo']->getTypeReduction() == 'montant') {
  202.                 
  203.                 $montant_total_ttc $montant_total_ttc $cart['code_promo']->getReduction();
  204.                 $montant_total_tva $montant_total_ttc - ($montant_total_ttc 1.2 );
  205.                 // $montantPromoPanier = $cart['code_promo']->getReduction();
  206.             }
  207.         }
  208.         if(in_array('anniversaire',$formulesArray)) {
  209.             $creneau_anniv $cart_details['anniversaire']['forfaits'][0]['infos_anniv']['creneau_anniv'];
  210.             $creneauAnniversaire $date_arrive;
  211.             $creneauAnniversaire->add(new \DateInterval('PT'.strtoupper($creneau_anniv).'M')); 
  212.             $reservation->setDateResa($creneauAnniversaire);
  213.             if(isset($cart['birthday_customer_comment']) && $cart['birthday_customer_comment']) {
  214.                 $reservation->setBirthdayCustomerComment($cart['birthday_customer_comment']);
  215.             }
  216.         } else {
  217.             $reservation->setDateResa($date_arrive);
  218.         }
  219.         /************************************************/  
  220.         /************************************************/  
  221.         
  222.         $reservation->setFormule($formulesString);
  223.         $request Request::createFromGlobals();
  224.         $reservation->setIp($request->getClientIp());
  225.         $reservation->setSstotalHT(round($montant_total_ttc $montant_total_tva2));
  226.         $reservation->setTVA(round($montant_total_tva2));
  227.         $reservation->setTotalTTC(round($montant_total_ttc2));
  228.         $reservation->setActive(0);
  229.         if($action_paiement == "carte_1055")  {
  230.             $reservation->setStatut('Paiement carte 1055');
  231.             $reservation->setActive(1);
  232.             $comment "<b>Titulaire carte 1055</b> : ";
  233.             if(isset($infos['titulaire_carte_1055']) && !empty($infos['titulaire_carte_1055'])) $comment .= $infos['titulaire_carte_1055'];
  234.             if(isset($infos['numero_carte_1055']) && !empty($infos['numero_carte_1055'])) $comment .= " (Mail: ".$infos['numero_carte_1055'].")";
  235.             $reservation->setComment($comment);
  236.         } elseif($action_paiement == "panier_precommande" && round($montant_total_ttc,0) == 0)  {
  237.             $reservation->setStatut('Payé');
  238.             $reservation->setActive(1);
  239.         } else {
  240.             $reservation->setStatut('Attente de paiement');
  241.         }
  242.         $reservation->setDeleted(0);
  243.         if(in_array('anniversaire',$formulesArray)) {
  244.             $comment "";
  245.             if($reservation->getComment()) {
  246.                 $comment .= $reservation->getComment();
  247.                 $comment .= "\n============================\n";
  248.             }
  249.             $comment .= $cart_details['anniversaire']['forfaits'][0]['infos_anniv']['commentaire'];
  250.             // TO-DO calculer l'acompte ===================
  251.             if ($json_total_a_payer != "" && $json_total_a_payer != null && $json_total_a_payer != $json_total_panier
  252.                 $comment .= "\nAcompte : " . ($json_total_a_payer 100) . " € ";
  253.             $reservation->setComment($comment);
  254.             if($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']) {
  255.                 $reservation->setChildName($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['name_child']);
  256.                 $reservation->setChildBirthday($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['birthday_child']);
  257.                 $reservation->setChildAge($cart_details['anniversaire']['forfaits'][0]['infos_anniv']['anniversaire_obj']['age_child']);
  258.             }
  259.         }
  260.         $em->persist($reservation);
  261.         $em->flush();
  262.         
  263.         $reservation_id =  (int)$reservation->getId();
  264.         $reservation_number $reservation->getNumeroResa();
  265.             
  266.         foreach($cart_details as $key => $formule) {
  267.             foreach($formule['forfaits'] as $forfaitArray) {
  268.             
  269.                 $forfait $forfaitArray['obj_forfait'];
  270.                 $resaDetailsArgs = array(
  271.                     'Reservation' => $reservation,
  272.                     'Designation' => 'Forfait : ' $forfait->getDesignation(),
  273.                     'CodeActivity' => null,
  274.                     'Date' => $date_arrive,
  275.                     'Creneau' => null,
  276.                     'Quantity' => null,
  277.                     'PuTTC' => null,
  278.                     'TauxTVA' => null,
  279.                     'TotalHt' => $forfaitArray['total_ttc'] - $forfaitArray['total_tva'],
  280.                     'MontantTva' => $forfaitArray['total_tva'],
  281.                     'TotalTTC' => $forfaitArray['total_ttc'],
  282.                     'Parent' => null,
  283.                 );
  284.                 $resaDetails $this->addReservationDetail($resaDetailsArgs);
  285.                 
  286.                 foreach($forfaitArray['tarifs'] as $tarifArray) {
  287.                     $tarif $tarifArray['obj_tarif'];
  288.                     if($tarif) {
  289.                         $tarifDetailsArgs = array(
  290.                             'Reservation' => $reservation,
  291.                             'Designation' => 'Tarif : '$tarif->getDesignation(),
  292.                             'CodeActivity' => null,
  293.                             'Date' => $date_arrive,
  294.                             'Creneau' => null,
  295.                             'Quantity' => $tarifArray['qty'],
  296.                             'PuTTC' => $tarif->getPriceTtc(),
  297.                             'TauxTVA' => $tarif->getTauxTva(),
  298.                             'TotalHt' => null,
  299.                             'MontantTva' => null,
  300.                             'TotalTTC' => null,
  301.                             'Parent' => $resaDetails,
  302.                         );
  303.                         $tarifDetails $this->addReservationDetail($tarifDetailsArgs);
  304.                     }
  305.                 }
  306.                 
  307.                 foreach($forfaitArray['options'] as $optionArray) {
  308.                     $option $optionArray['obj_option'];
  309.                     if($option) {
  310.                         $optionDetailsArgs = array(
  311.                             'Reservation' => $reservation,
  312.                             'Designation' => 'Option : '$option->getDesignation(),
  313.                             'CodeActivity' => null,
  314.                             'Date' => $date_arrive,
  315.                             'Creneau' => null,
  316.                             'Quantity' => $optionArray['qty'],
  317.                             'PuTTC' => $option->getPriceTtc(),
  318.                             'TauxTVA' => $option->getTauxTva(),
  319.                             'TotalHt' => null,
  320.                             'MontantTva' => null,
  321.                             'TotalTTC' => null,
  322.                             'Parent' => $resaDetails,
  323.                         );
  324.                         $optionDetails $this->addReservationDetail($optionDetailsArgs);
  325.                     }
  326.                 }
  327.                 
  328.                 if(isset($forfaitArray['activity'])) {
  329.                     foreach($forfaitArray['activity'] as $activityArray) {
  330.                         $activity $activityArray['obj_activity'];
  331.                         $bookedActivity = new BookedActivity();
  332.                         $bookedActivity->setFormule($formule['obj_formule']->getCode());
  333.                         $bookedActivity->setForfait($forfait->getDesignation());
  334.                         
  335.                         $activitySearch $em->getRepository(Activity::class)->find($activity->getId());
  336.                         if($activitySearch)
  337.                         {
  338.                             $bookedActivity->setCodeActivity($activitySearch->getCode());
  339.                             $bookedActivity->setDesignation($activitySearch->getDesignation());
  340.                         } else {
  341.                             $bookedActivity->setCodeActivity(Tools::str2url($activity->getDesignation()));
  342.                             $bookedActivity->setDesignation($activity->getDesignation());
  343.                         }
  344.                             
  345.                         if(isset($activityArray['creneau'])) {
  346.                             $creneau_activity $activityArray['creneau'];
  347.                             $creneauActivity = new \DateTime($date_arrive->format('Y-m-d'));
  348.                             $creneauActivity->add(new \DateInterval('PT'.strtoupper($creneau_activity).'M')); 
  349.                             
  350.                             $creneauActivity_Check = new \DateTime($date_arrive->format('Y-m-d'));
  351.                             $creneauActivity_Check->add(new \DateInterval('P1D')); 
  352.                             $creneauActivity_Check->add(new \DateInterval('PT'.strtoupper($creneau_activity).'M')); 
  353.                             $interval $creneauActivity->diff($creneauActivity_Check);
  354.                             if($interval->format('%R%h') == '+1') {
  355.                                 $creneauActivity->add(new \DateInterval('PT1H')); 
  356.                             } elseif( $interval->format('%R%h') == '-1') {
  357.                                 $creneauActivity->sub(new \DateInterval('PT1H')); 
  358.                             }
  359.                             
  360.                             $bookedActivity->setDate($creneauActivity);
  361.                             $bookedActivity->setCreneau($creneauActivity);
  362.                         } else {
  363.                             $bookedActivity->setDate($date_arrive);
  364.                             //TO-DO : voir si on réserve toutes les activités au créneau de l'anniversaire ou non
  365.                             if(in_array('anniversaire',$formulesArray)) {
  366.                                 $bookedActivity->setCreneau($creneauAnniversaire);  
  367.                             }
  368.                             // =========================================================================
  369.                         }
  370.                         $bookedQty = (isset($activityArray['parties'])) ? $activityArray['qty'] : ($activityArray['qty'] / $activityArray['parties']);
  371.                         $bookedActivity->setQuantity($bookedQty);
  372.                         // $bookedActivity->setQuantity($activityArray['qty']);
  373.                         $bookedActivity->setNbreParties($activityArray['parties']);
  374.                         $bookedActivity->setReservation($reservation);
  375.                         $bookedActivity->setAdmin(0);
  376.                         $em->persist($bookedActivity);
  377.                         $em->flush();
  378.                     }
  379.                 }   
  380.             }
  381.         }
  382.         
  383.         if(isset($cart['bon_numerique'])) {
  384.             foreach ($cart['bon_numerique'] as $key => $bon) {
  385.                 $bonDetails = new ReservationDetails();
  386.                 $bonDetails->setDesignation('E-ticket : '.$bon['bon'].' ('.$bon['total'].')');
  387.                 $bonDetails->setDate($date_arrive);
  388.                 $bonDetails->setReservation($reservation);
  389.                 $bonDetails->setTotalTTC(round($bon['total'],2));
  390.                 $em->persist($bonDetails);
  391.                 $em->flush();
  392.             }
  393.         }
  394.         
  395.         if(isset($cart['code_promo'])) {
  396.             if($cart['code_promo']->getTypeReduction() == 'percentage'$montantPromoPanier '-'.($cart['code_promo']->getPercent()*100).'%';
  397.             elseif($cart['code_promo']->getTypeReduction() == 'montant'$montantPromoPanier '-'.$cart['code_promo']->getReduction().'€';
  398.             $promoPanierDetails = new ReservationDetails();
  399.             $promoPanierDetails->setDesignation('Code promo : '.$cart['code_promo']->getCode().' ('.$montantPromoPanier.')');
  400.             $promoPanierDetails->setDate($date_arrive);
  401.             $promoPanierDetails->setReservation($reservation);
  402.             if($cart['code_promo']->getTypeReduction() == 'percentage') {
  403.                 $montant_reduction round(- ($reservation->getTotalTTC()*$cart['code_promo']->getPercent()),2);
  404.             } else if($cart['code_promo']->getTypeReduction() == 'montant') {
  405.                 $montant_reduction round($cart['code_promo']->getReduction(),2);
  406.             }
  407.             $promoPanierDetails->setTotalTTC($montant_reduction);
  408.             $em->persist($promoPanierDetails);
  409.             $em->flush();
  410.         }
  411.         
  412.         $em->persist($reservation);
  413.         $em->flush();
  414.         //Historique de solde
  415.         $history_resa = new History();
  416.         if($customer instanceof Customer)
  417.         {
  418.             $history_resa->setCustomerId($customer->getId());
  419.             $history_resa->setInformation("Réservation " $reservation_number " (#" $reservation_id ")"); 
  420.             $resa_total_ttc abs($reservation->getTotalTTC()) * -1;
  421.             $history_resa->setMouvement($resa_total_ttc);
  422.             $history_resa->setReservation($reservation);
  423.             $em->persist($history_resa);
  424.             $em->flush();
  425.         }
  426.         
  427.         // dd($forfaitArray['activity']);
  428.         return $reservation;
  429.     }   
  430.     
  431.      /**
  432.      * @Route("/createpaiement", methods={"POST"}, name="booking_createpaiement")
  433.      * Cette fonction permet de créer le formulaire de paiement
  434.      */
  435.     public function createPaiement(Request $request)
  436.     {
  437.         // action_paiement : - carte_payplug
  438.         //                   - carte_1055
  439.         // dd($this->secretkey[$this->paiement_mode]);
  440.         $data json_decode($request->request->get('data'));
  441.         $error false;
  442.         $action_paiement $data->action_paiement;
  443.         $json_total_panier $data->total_panier;
  444.         $json_total_a_payer $data->total_a_payer;
  445.         $titulaire_carte_1055 $data->titulaire_carte_1055;
  446.         $numero_carte_1055 $data->numero_carte_1055;
  447.         $infos = array();
  448.         if($titulaire_carte_1055$infos['titulaire_carte_1055'] = $titulaire_carte_1055;
  449.         if($numero_carte_1055$infos['numero_carte_1055'] = $numero_carte_1055;
  450.         $reservation $this->createReservation($action_paiement$infos$json_total_a_payer$json_total_panier);
  451.         $reservation_id =  (int)$reservation->getId();
  452.         $reservation_number $reservation->getNumeroResa();
  453.         $total_a_payer $reservation->getTotalTTC();
  454.         $customer $this->container->get('security.token_storage')->getToken()->getUser();
  455.         $customer_number $customer->getCustomerNumber();
  456.         
  457.         $return_url $this->generateUrl('success', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  458.         $cancel_url $this->generateUrl('cancel', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  459.         $notification_url $this->generateUrl('notification', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  460.         if($action_paiement == "carte_1055") {
  461.             file_get_contents($notification_url '?idresa='.$reservation_number."&p=1");
  462.             $data->return_url $return_url '?idresa='.$reservation_number."&p=1";
  463.         } else if($action_paiement == "panier_precommande") {
  464.             file_get_contents($notification_url '?idresa='.$reservation_number."&pre=1");
  465.             $data->return_url $return_url '?idresa='.$reservation_number."&pre=1";
  466.         } else if($action_paiement == "carte_payplug") {
  467.             $vendor_dir str_replace('src','vendor',dirname(__DIR__));
  468.             require_once($vendor_dir '/payplug/payplug-php/lib/init.php');
  469.             // \Payplug\Payplug::setSecretKey($this->secretkey);
  470.             \Payplug\Payplug::init(array(
  471.               'secretKey' => $this->secretkey[$this->paiement_mode],
  472.             ));
  473.             if($customer->getEmail() != "")
  474.                 $email $customer->getEmail();
  475.             else
  476.                 $error 'no email';
  477.             if( $customer->getPhoneMobile() != "") {
  478.                 $phoneMobile str_replace(' ','',$customer->getPhoneMobile());
  479.                 $phoneMobile str_replace('.','',$phoneMobile);
  480.                 $phoneMobile str_replace('-','',$phoneMobile);
  481.                 if(strlen($phoneMobile) == 10 && strpos($customer->getPhoneMobile(),'+') === false) {
  482.                     $phoneMobile '+33'.substr($phoneMobile,1);
  483.                 } elseif(substr($phoneMobile02) === "00" && strlen($phoneMobile) == 13) {
  484.                     $phoneMobile '+'.substr($phoneMobile2);
  485.                 }
  486.             }   
  487.             else
  488.                 $error 'no mobile phone';
  489.             
  490.             $firstname $customer->getFirstname();
  491.             $lastname $customer->getLastname();
  492.             $address1 $customer->getAddress1();
  493.             $address2 = ($customer->getAddress2() != "") ? $customer->getAddress2() : null;
  494.             $postcode $customer->getPostcode();
  495.             $city $customer->getCity();
  496.             $country $customer->getCountry();
  497.             // if (isset($reservation->acompte_paiement) && ($reservation->acompte_paiement) > 0) 
  498.             //     $amount = intval(number_format($reservation->acompte_paiement * 100, 0, '.', ''));
  499.             // elseif (isset($reservation->total_a_payer) && ($reservation->total_a_payer) > 0) 
  500.             //     $amount = intval(number_format($reservation->total_a_payer * 100, 0, '.', ''));
  501.             // else 
  502.             //     $error = 'no amount';
  503.             
  504.             if($total_a_payer != ($json_total_a_payer/100) && ((int) round($total_a_payer*100,0)) == $json_total_panier) {
  505.                 $amount $json_total_a_payer;
  506.             } else {
  507.                 $amount = (int) round($total_a_payer*100,0);
  508.             }
  509.             $arg_payplug = array(
  510.                 'amount'         => $amount,
  511.                 'currency'       => 'EUR',
  512.                 // 'save_card'      => true, // TO-DO : change to true en mode PROD si 1055 OK
  513.                 'billing'       => array(
  514.                     'first_name' => $firstname,
  515.                     'last_name'  => $lastname,
  516.                     'email'      => $email,
  517.                     'address1'   => $address1,
  518.                     'address2'   => $address2,
  519.                     'mobile_phone_number'    => $phoneMobile,
  520.                     'city'       => $city,
  521.                     'postcode'   => $postcode,
  522.                     'country'    => $country,
  523.                     'language' => 'fr',
  524.                 ),
  525.                 'shipping'       => array(
  526.                     'email'      => $email,
  527.                     'first_name' => $firstname,
  528.                     'last_name'  => $lastname,
  529.                     'address1'   => $address1,
  530.                     'address2'   => $address2,
  531.                     'mobile_phone_number'    => $phoneMobile,
  532.                     'city'       => $city,
  533.                     'postcode'   => $postcode,
  534.                     'country'    => $country,
  535.                     'language' => 'fr',
  536.                     'delivery_type'  => 'TRAVEL_OR_EVENT'// OTHER ou BILLING
  537.                 ),
  538.                 'hosted_payment' => array(
  539.                     'return_url' => $return_url '?idresa='.$reservation_number,
  540.                     'cancel_url' => $cancel_url '?idresa='.$reservation_number,
  541.                 ),
  542.                 'notification_url' => $notification_url '?idresa='.$reservation_number,
  543.                 'metadata'        => array(
  544.                     'customer_number'       => $customer_number,
  545.                     'reservation_id'        => $reservation_id,
  546.                     'reservation_number'    => $reservation_number
  547.                 )
  548.             );
  549.             // dd($arg_payplug);
  550.             
  551.             try{
  552.                 $payment = \Payplug\Payment::create($arg_payplug);
  553.             }
  554.             catch(\Exception $e){
  555.                 $error serialize($arg_payplug);
  556.             }
  557.             if(!$error){
  558.                 $data->payment_url $payment->hosted_payment->payment_url;
  559.                 $data->payment_id $payment->id;
  560.                 $em $this->getDoctrine()->getManager();
  561.                 $reservation->setPaymentId($payment->id);
  562.                 $today = new \DateTime('now');
  563.                 $history $reservation->getHistory();    
  564.                 $request Request::createFromGlobals();
  565.                 $history .= $request->headers->get('User-Agent')."\n".'--------------------------'."\n";             
  566.                 $history .= $today->format("d/m/Y H:i:s") . " : Transaction créée (" $payment->id ")\n";
  567.                 $reservation->setHistory($history);
  568.                 $em->persist($reservation);
  569.                 $em->flush();
  570.             }
  571.         }
  572.         if(!$error){
  573.             $today = new \DateTime('now');
  574.             $em $this->getDoctrine()->getManager();
  575.             $cartSession $em->getRepository(CartSession::class)->findOneBy(['id_cart_session' => $customer->getId().'_'.$today->format('Ymd')]);
  576.             if($cartSession instanceof CartSession) {
  577.                 $em->remove($cartSession);
  578.                 $em->flush();
  579.             }
  580.         }
  581.         
  582.         if ($error) {
  583.             return new JsonResponse(['error' => $error'data' => $arg_payplug], JsonResponse::HTTP_CREATED);
  584.         } else {
  585.             return new JsonResponse($dataJsonResponse::HTTP_CREATED);         
  586.         }
  587.     }
  588.     /**
  589.      * @Route("/success", methods={"GET", "POST"}, name="success")
  590.      * Cette fonction permet d'afficher la page de succès après paiement réussi
  591.      */
  592.     public function successAction(Request $requestMailerInterface $mailer)
  593.     {
  594.         $cart $this->ss->get();
  595.         $this->ss->empty();
  596.         $vendor_dir str_replace('src','vendor',dirname(__DIR__));
  597.         require_once($vendor_dir '/payplug/payplug-php/lib/init.php');
  598.         \Payplug\Payplug::init(array(
  599.           'secretKey' => $this->secretkey[$this->paiement_mode],
  600.         ));
  601.         /* GET Method */
  602.         $reservation_number $request->query->get('idresa');
  603.         $carte_1055 = ($request->query->get('p') != null && $request->query->get('p') == '1') ? true false;
  604.         $panier_precommande = ($request->query->get('pre') != null && $request->query->get('pre') == '1') ? true false;
  605.         $reservation_date null;
  606.         $transaction_ok null;
  607.         $failure_id null;
  608.         $error null;
  609.         $print_url $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  610.         $print_url .= '?idresa=';
  611.         if($reservation_number != null && $reservation_number != ""
  612.         {
  613.             $em $this->getDoctrine()->getManager();
  614.             $reservation $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
  615.         
  616.             if (!$reservation) {
  617.                 $error 'Aucune réservation trouvée. Veuillez nous contacter par téléphone.';
  618.             }
  619.             if($reservation instanceof Reservation)
  620.             {
  621.                 $payment_id $reservation->getPaymentId();
  622.                 $reservation_number $reservation->getNumeroResa();
  623.                 $reservation_date $reservation->getDateResa();
  624.                 $reservation_montant_ht $reservation->getSstotalHT();     
  625.                 $reservation_montant $reservation->getTotalTTC();   
  626.                 $transaction_ok false;
  627.                 $print_url .= $reservation_number;
  628.                             
  629.                 $reservation_regle 0;
  630.                 if($payment_id != null && $payment_id != "" && $this->paiement_mode != "test")
  631.                 {
  632.                     $payment = \Payplug\Payment::retrieve($payment_id);
  633.                     
  634.                     if($payment->is_paid && $payment->failure == null) {
  635.                         $transaction_ok true;
  636.                         $reservation_regle $payment->amount 100;
  637.                     } elseif(!$payment->is_paid && $payment->failure != null) {
  638.                         $failure_id $payment->failure->message;
  639.                     }
  640.                 }
  641.                 if($carte_1055) {
  642.                     $print_url .= "&p=1";
  643.                 }
  644.                 // ##################
  645.                 // Compostage Voucher
  646.                 if(($carte_1055 || $transaction_ok || (float) $reservation_montant == 0) && isset($cart['bon_numerique'])) {
  647.                     foreach ($cart['bon_numerique'] as $key => $bon) {
  648.                         $data $this->vs->getVoucher($bon['bon']);
  649.                         if ( $data['_remaining_value'] != && $data['status'] == "wcpdf-active") {
  650.                             $target $bon['bon'];
  651.                             $quantity = isset($bon['qty']) ? $bon['qty'] : '';
  652.                             $amount = isset($bon['bon_total']) ? $bon['bon_total'] : '';
  653.                             if($data['unlimited_voucher']) {
  654.                                 $amount $bon['total'] / 1.1;
  655.                             }
  656.                             $param 'action=set&target='.$target.'&quantity='.$quantity.'&amount='.$amount.'&user='.$this->user_id_boutique.'&demandeur=client';
  657.                             $result $this->vs->getData($param);
  658.                         } 
  659.                     }
  660.                 
  661.                 }
  662.                 // FIN Compostage Voucher
  663.                 // ##################
  664.                 
  665.             }
  666.         } else $error "Votre numéro de réservation n'est pas indiqué ou il est non valide.";
  667.     
  668.         $formules explode(',',$reservation->getFormule());
  669.         return $this->render('paiement/success.html.twig', array(
  670.             'environnement' => $this->paiement_mode,
  671.             'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null ,
  672.             'creneau_resa' => ($reservation_date != null && in_array('anniversaire',$formules)) ? $reservation_date->format('H:i') : null ,
  673.             'reservation' => $reservation,
  674.             'carte_1055' => $carte_1055,
  675.             'panier_precommande' => $panier_precommande,
  676.             'transaction_ok' => $transaction_ok,
  677.             'reservation_regle' => number_format($reservation_regle2','' ') . ' €',
  678.             'reservation_montant' => number_format($reservation_montant2','' ') . ' €',
  679.             'reservation_montant_tva' => number_format(($reservation_montant $reservation_montant_ht), 2','' ') . ' €',
  680.             'reservation_montant_ht' => number_format($reservation_montant_ht2','' ') . ' €',
  681.             'print_url' => $print_url,
  682.             'failure_id' => $failure_id,
  683.             'error' => $error
  684.         ));
  685.     }
  686.     /**
  687.      * @Route("/cancel", methods={"GET", "POST"}, name="cancel")
  688.      * Cette fonction permet d'afficher la page de paiement annulé
  689.      */
  690.     public function cancelAction(Request $request)
  691.     {
  692.         $vendor_dir str_replace('src','vendor',dirname(__DIR__));
  693.         require_once($vendor_dir '/payplug/payplug-php/lib/init.php');
  694.         \Payplug\Payplug::init(array(
  695.           'secretKey' => $this->secretkey[$this->paiement_mode],
  696.         ));
  697.         $reservation_number $request->query->get('idresa');
  698.         if($reservation_number != null && $reservation_number != ""
  699.         {
  700.             $em $this->getDoctrine()->getManager();
  701.             $reservation $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
  702.             $resource = \Payplug\Payment::retrieve($reservation->getPaymentId());
  703.             $payment_id $resource->id;
  704.             $payment_amount $resource->amount 100;
  705.             $payment_amount_format number_format($resource->amount 1002','' ');
  706.             if($reservation instanceof Reservation && $reservation->getPaymentId() == $payment_id ) {
  707.                 $customer_number $reservation->getCustomerNumber();
  708.                 $cm $this->getDoctrine()->getManager("customer");
  709.                 $customer $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
  710.             
  711.                 if ($resource instanceof \Payplug\Resource\Payment && !$resource->is_paid)
  712.                 {
  713.                     $message_error $this->getErrorMsgPayplug($resource->failure->code);
  714.                     // $reservation->setStatut('Payé');
  715.                     $failure_code 'non disponible';
  716.                     if($resource->failure != null && ($resource->failure->code == 'aborted' || $resource->failure->code == 'timeout')){
  717.                         $failure_code $resource->failure->code;
  718.                         $reservation->setStatut('Abandon');
  719.                     } else {
  720.                         $reservation->setStatut('Erreur paiement');
  721.                     }
  722.                     $dateTimeZone = new \DateTimeZone('Europe/Paris');
  723.                     $today = new \DateTime('now'$dateTimeZone);
  724.                     $history $reservation->getHistory();  
  725.                     $history .= $today->format("d/m/Y H:i:s") . " : Transaction échoué de " $payment_amount_format " € (" $payment_id ")\n";
  726.                     $history .= "------------------- : Payplug #(".$message_error.")\n";
  727.                     $reservation->setHistory($history);
  728.                     $history_solde = new History();
  729.                     
  730.                     if($customer instanceof Customer)
  731.                     {
  732.                         $history_solde->setCustomerId($customer->getId());
  733.                         $history_solde->setInformation("Erreur PAYPLUG : " $reservation_number " (" $payment_id ") [".$failure_code."]");
  734.                         $history_solde->setMouvement($payment_amount);
  735.                         $history_solde->setReservation($reservation);
  736.                         $em->persist($history_solde);
  737.                     }
  738.                 }
  739.             }
  740.             $em->persist($reservation);
  741.             $em->flush();
  742.         }
  743.         return $this->redirectToRoute('payment');
  744.     }
  745.     private function getErrorMsgPayplug($error_code
  746.     {
  747.         switch ($error_code) {
  748.             case 'processing_error':
  749.                 $error_msg "Erreur lors du traitement de la carte.";
  750.                 break;
  751.             case 'card_declined':
  752.                 $error_msg "La banque du client a refusé la demande de paiement.";
  753.                 break;
  754.             case '3ds_declined':
  755.                 $error_msg "La requête d'authentification 3D Secure a échoué";
  756.                 break;
  757.             case 'insufficient_funds':
  758.                 $error_msg "La carte a atteint son plafond autorisé";
  759.                 break;
  760.             case 'incorrect_number':
  761.                 $error_msg "Les informations de la carte sont incorrectes (numéro, date d’exp. ou le CVV)";
  762.                 break;
  763.             case 'fraud_suspected':
  764.                 $error_msg "Paiement refusé car une fraude a été détectée.";
  765.                 break;
  766.             case 'method_unsupported':
  767.                 $error_msg "Le moyen de paiement n'est pas supporté";
  768.                 break;
  769.             case 'card_scheme_mismatch':
  770.                 $error_msg "Le numéro de carte ne correspond pas à la marque sélectionnée.";
  771.                 break;
  772.             case 'card_expiration_date_prior_to_last_installment_date':
  773.                 $error_msg "La date d'expiration de la carte est antérieure à la date du dernier versement.";
  774.                 break;
  775.             case 'aborted':
  776.                 $error_msg "Le paiement a été abandonné";
  777.                 break;
  778.             case 'timeout':
  779.                 $error_msg "Le client n'a pas essayé de payer et a quitté la page de paiement.";
  780.                 break;
  781.             
  782.             default:
  783.                 $error_msg "Erreur de paiement";
  784.                 break;
  785.         }
  786.         return $error_msg;
  787.     }
  788.     /**
  789.      * @Route("/notification", methods={"GET", "POST"}, name="notification")
  790.      * Cette fonction permet d'afficher la page de succès après paiement réussi
  791.      */
  792.     public function notificationAction(Request $requestMailerInterface $mailer)
  793.     {
  794.         $vendor_dir str_replace('src','vendor',dirname(__DIR__));
  795.         require_once($vendor_dir '/payplug/payplug-php/lib/init.php');
  796.         \Payplug\Payplug::init(array(
  797.           'secretKey' => $this->secretkey[$this->paiement_mode],
  798.         ));
  799.         $error null;
  800.         // $input = file_get_contents('php://input');
  801.         $idresa $request->query->get('idresa');
  802.         $carte_1055 = ($request->query->get('p') != null && $request->query->get('p') == '1') ? true false;
  803.         $panier_precommande = ($request->query->get('pre') != null && $request->query->get('pre') == '1') ? true false;
  804.         $em $this->getDoctrine()->getManager();
  805.         $reservationVerif $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $idresa]);
  806.         // $resource = \Payplug\Payment::retrieve($reservationVerif->getPaymentId());
  807.         // $input = file_get_contents('php://input');
  808.         
  809.         try {
  810.             // $resource = \Payplug\Notification::treat($input);
  811.             if($reservationVerif->getPaymentId() != "") {
  812.                 $resource = \Payplug\Payment::retrieve($reservationVerif->getPaymentId());
  813.                 // $payment_id = 'pay_1GJ2PMEWFPSIgfNbeWkv9a'; $resource = \Payplug\Payment::retrieve($payment_id); // POUR DEBUG
  814.                 if ($resource instanceof \Payplug\Resource\Payment)
  815.                 {
  816.                     $payment_id $resource->id;
  817.                     $payment_state $resource->is_paid;
  818.                     $payment_date $resource->hosted_payment->paid_at;
  819.                     $payment_amount $resource->amount 100;
  820.                     $payment_amount_format number_format($resource->amount 1002','' ');
  821.                     if (isset($resource->metadata['customer_number'])) $customer_number $resource->metadata['customer_number'];
  822.                     if (isset($resource->metadata['customer_id'])) $customer_number $resource->metadata['customer_id'];
  823.                     $reservation_id $resource->metadata['reservation_id'];
  824.                     $reservation_number $resource->metadata['reservation_number'];
  825.                     $failure_id $resource->failure;
  826.                     $reservation $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
  827.                     
  828.                     if($reservation instanceof Reservation && $reservation->getPaymentId() == $payment_id && !$reservation->getActive())
  829.                     {
  830.                         $customer_number $reservation->getCustomerNumber();
  831.                         $cm $this->getDoctrine()->getManager("customer");
  832.                         $customer $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
  833.                         
  834.                         if($resource->is_paid && $resource->failure == null
  835.                         {
  836.                             $reservation->setStatut('Payé');
  837.                             $reservation->setActive(1);                     
  838.                             $dateTimeZone = new \DateTimeZone('Europe/Paris');
  839.                             $today = new \DateTime('now'$dateTimeZone);
  840.                             $history $reservation->getHistory();  
  841.                             $history .= $today->format("d/m/Y H:i:s") . " : Transaction réussie de " $payment_amount_format " € (" $payment_id ")\n";
  842.                             $reservation->setHistory($history);
  843.                             $history_solde = new History();
  844.                             // $customer = $em->getRepository(Customer::Class)->findOneBy(['customerNumber' => $customer_number]);
  845.                             
  846.                             if($customer instanceof Customer)
  847.                             {
  848.                                 $history_solde->setCustomerId($customer->getId());
  849.                                 $history_solde->setInformation("Paiement PAYPLUG : " $reservation_number " (" $payment_id ")");
  850.                                 $history_solde->setMouvement($payment_amount);
  851.                                 $history_solde->setReservation($reservation);
  852.                                 $em->persist($history_solde);
  853.                             }
  854.                             //Envoi des emails
  855.                             $transaction_ok true;
  856.                             $comment $reservation->getComment();  
  857.                             // if(strpos($comment,'Titulaire carte 1055') !== false) {
  858.                             //     $transaction_ok = 'carte_1055';
  859.                             // }
  860.                             $reservation_date $reservation->getDateResa();
  861.                             $reservation_montant_ht $reservation->getSstotalHT();
  862.                             $reservation_montant $reservation->getTotalTTC();
  863.                             $reservation_regle $resource->amount 100;
  864.                             $print_url $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);   
  865.                 
  866.                             $message = (new Email())
  867.                             ->subject('Votre réservation au 1055 : ' $reservation_number)
  868.                             ->from('reservationbesancon@1055.fr')
  869.                             ->to($customer->getEmail())
  870.                             ->cc('reservationbesancon@1055.fr')
  871.                             ->replyTo('besancon@1055.fr')
  872.                             // ->addCc('dev@publigo.fr')
  873.                             ->html(
  874.                                 $this->renderView(
  875.                                     'email/confirmation.html.twig',
  876.                                     array(
  877.                                         'email' => strtolower($customer->getEmail()),
  878.                                         'firstname' => ucfirst($customer->getFirstname()),
  879.                                         'lastname' => strtoupper($customer->getLastname()),
  880.                                         'address1' => strtoupper($customer->getAddress1()),
  881.                                         'address2' => strtoupper($customer->getAddress2()),
  882.                                         'postcode' => $customer->getPostcode(),
  883.                                         'city' => strtoupper($customer->getCity()),
  884.                                         'phone' => $customer->getPhone(),
  885.                                         'phoneMobile' => $customer->getPhoneMobile(),
  886.                                         'reservation' => $reservation,
  887.                                         'infos_resa' => $reservation->getComment(),
  888.                                         'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null,
  889.                                         'creneau_resa' => ($reservation_date != null && $reservation->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
  890.                                         'numero_resa' => $reservation_number,
  891.                                         'carte_1055' => false,
  892.                                         'panier_precommande' => false,
  893.                                         'transaction_ok' => $transaction_ok,
  894.                                         'reservation_regle' => number_format($reservation_regle2','' ') . ' €',
  895.                                         'reservation_montant' => number_format($reservation_montant2','' ') . ' €',
  896.                                         'reservation_montant_tva' => number_format(($reservation_montant $reservation_montant_ht), 2','' ') . ' €',
  897.                                         'reservation_montant_ht' => number_format($reservation_montant_ht2','' ') . ' €',
  898.                                         'print_url' => $print_url '?idresa='.$reservation_number,
  899.                                         'failure_id' => $failure_id,
  900.                                         'error' => $error
  901.                                     )
  902.                                 )
  903.                             );
  904.                             $mailer->send($message);
  905.                         
  906.                             $em->persist($reservation);
  907.                             $em->flush();
  908.                         } else {
  909.                             $cancel_url $this->generateUrl('cancel', array(), UrlGeneratorInterface::ABSOLUTE_URL);
  910.                             // $cancel_url . '?idresa='.$reservation_number
  911.                             return $this->redirectToRoute('cancel',array('idresa' => $reservation_number));
  912.                         }
  913.                         
  914.                         $em->persist($reservation);
  915.                         $em->flush();
  916.                     }
  917.                 } 
  918.             } 
  919.             if($carte_1055 || $panier_precommande) {
  920.                 if($reservationVerif instanceof Reservation )
  921.                 {
  922.                     $customer_number $reservationVerif->getCustomerNumber();
  923.                     $cm $this->getDoctrine()->getManager("customer");
  924.                     $customer $cm->getRepository(Customer::class)->findOneBy(['customerNumber' => $customer_number]);
  925.                     $today = new \DateTime('now');
  926.                     $history $reservationVerif->getHistory();
  927.                     $request Request::createFromGlobals();
  928.                     $history .= $request->headers->get('User-Agent')."\n".'--------------------------'."\n";   
  929.                     if($carte_1055$history .= $today->format("d/m/Y H:i:s") . " : Demande de paiement par Carte 10 55\n";
  930.                     else if($panier_precommande$history .= $today->format("d/m/Y H:i:s") . " : Paiement par bon numérique\n";
  931.                     $reservationVerif->setHistory($history);
  932.                     $failure_id false;
  933.                     $transaction_ok $carte_1055 $carte_1055 $panier_precommande;
  934.                     $comment $reservationVerif->getComment(); 
  935.                     $reservation_date $reservationVerif->getDateResa();
  936.                     $reservation_montant_ht $reservationVerif->getSstotalHT();
  937.                     $reservation_montant $reservationVerif->getTotalTTC();
  938.                     $reservation_regle 0;
  939.                     $print_url $this->generateUrl('print', array(), UrlGeneratorInterface::ABSOLUTE_URL);   
  940.         
  941.                     $message = (new Email())
  942.                     ->subject('Votre réservation au 1055 : ' $idresa)
  943.                     ->from('reservationbesancon@1055.fr')
  944.                     ->to($customer->getEmail())
  945.                     ->cc('reservationbesancon@1055.fr')
  946.                     ->replyTo('besancon@1055.fr')
  947.                     // ->addCc('dev@publigo.fr')
  948.                     ->html(
  949.                         $this->renderView(
  950.                             'email/confirmation.html.twig',
  951.                             array(
  952.                                 'email' => strtolower($customer->getEmail()),
  953.                                 'firstname' => ucfirst($customer->getFirstname()),
  954.                                 'lastname' => strtoupper($customer->getLastname()),
  955.                                 'address1' => strtoupper($customer->getAddress1()),
  956.                                 'address2' => strtoupper($customer->getAddress2()),
  957.                                 'postcode' => $customer->getPostcode(),
  958.                                 'city' => strtoupper($customer->getCity()),
  959.                                 'phone' => $customer->getPhone(),
  960.                                 'phoneMobile' => $customer->getPhoneMobile(),
  961.                                 'reservation' => $reservationVerif,
  962.                                 'infos_resa' => $reservationVerif->getComment(),
  963.                                 'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null,
  964.                                 'creneau_resa' => ($reservation_date != null && $reservationVerif->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
  965.                                 'numero_resa' => $idresa,
  966.                                 'carte_1055' => $carte_1055,
  967.                                 'panier_precommande' => $panier_precommande,
  968.                                 'transaction_ok' => false,
  969.                                 'reservation_regle' => number_format($reservation_regle2','' ') . ' €',
  970.                                 'reservation_montant' => number_format($reservation_montant2','' ') . ' €',
  971.                                 'reservation_montant_tva' => number_format(($reservation_montant $reservation_montant_ht), 2','' ') . ' €',
  972.                                 'reservation_montant_ht' => number_format($reservation_montant_ht2','' ') . ' €',
  973.                                 'print_url' => $print_url '?idresa='.$idresa,
  974.                                 'failure_id' => $failure_id,
  975.                                 'error' => $error
  976.                             )
  977.                         )
  978.                     );
  979.                     $mailer->send($message);
  980.                     $em->persist($reservationVerif);
  981.                     $em->flush();
  982.                 }
  983.             }
  984.         }
  985.         catch (\Payplug\Exception\PayplugException $exception) {
  986.           echo $exception;
  987.         }
  988.         
  989.         return $this->render('paiement/notification.html.twig', array());
  990.     }
  991.     /**
  992.      * @Route("/print", methods={"GET", "POST"}, name="print")
  993.      * Cette fonction permet d'imprimer le PDF de réservation
  994.      */
  995.     public function printAction(Request $request)
  996.     {   
  997.         $vendor_dir str_replace('src','vendor',dirname(__DIR__));
  998.         require_once($vendor_dir '/payplug/payplug-php/lib/init.php');
  999.         \Payplug\Payplug::init(array(
  1000.           'secretKey' => $this->secretkey[$this->paiement_mode],
  1001.         ));
  1002.         /* GET Method */
  1003.         $reservation_number $request->query->get('idresa');
  1004.         $carte_1055 $request->query->get('p');
  1005.         $panier_precommande $request->query->get('pre');
  1006.         $error null;
  1007.         // $snappy = $this->get('knp_snappy.pdf');
  1008.         $pageUrl $this->generateUrl('home', array(), false);
  1009.         if($reservation_number != null && $reservation_number != ""
  1010.         {
  1011.             $em $this->getDoctrine()->getManager();
  1012.             $reservation $em->getRepository(Reservation::class)->findOneBy(['numeroResa' => $reservation_number]);
  1013.             $customer_id $reservation->getCustomerId();
  1014.             $cm $this->getDoctrine()->getManager("customer");
  1015.             $customer $cm->getRepository(Customer::class)->findOneBy(['id' => $customer_id]);
  1016.             if (!$reservation) {
  1017.                 $error 'Aucune réservation trouvée. Veuillez nous contacter par téléphone.';
  1018.             }
  1019.             if($reservation instanceof Reservation)
  1020.             {
  1021.                 $payment_id $reservation->getPaymentId();
  1022.                 $reservation_number $reservation->getNumeroResa();
  1023.                 $reservation_date $reservation->getDateResa();
  1024.                 $reservation_montant_ht $reservation->getSstotalHT();
  1025.                 $reservation_montant $reservation->getTotalTTC();
  1026.                 $transaction_ok false;
  1027.                 $failure_id false;    
  1028.                 
  1029.                 $reservation_regle 0;
  1030.                 if($payment_id != null && $payment_id != "")
  1031.                 {
  1032.                     $payment = \Payplug\Payment::retrieve($payment_id);
  1033.                     
  1034.                     if($payment->is_paid && $payment->failure == null) {
  1035.                         $transaction_ok true;
  1036.                         $reservation_regle $payment->amount 100;
  1037.                     } elseif(!$payment->is_paid && $payment->failure != null) {
  1038.                         $transaction_ok false;
  1039.                         $failure_id $payment->failure->message;
  1040.                     }
  1041.                 }
  1042.                 if($carte_1055) {
  1043.                     $transaction_ok 'carte_1055';
  1044.                 }
  1045.                 if($panier_precommande) {
  1046.                     $transaction_ok 'panier_precommande';
  1047.                 }
  1048.             }
  1049.         } else $error "Votre numéro de réservation n'est pas indiqué ou il est non valide.";
  1050.         return $this->render(
  1051.             'paiement/print.html.twig',
  1052.             array(
  1053.                 'environnement' => $this->paiement_mode,
  1054.                 'date_resa' => ($reservation_date != null) ? $reservation_date->format("d/m/Y") : null ,
  1055.                 'creneau_resa' => ($reservation_date != null && $reservation->getFormule() == 'anniversaire') ? $reservation_date->format('H:i') : null ,
  1056.                 'numero_resa' => $reservation_number,
  1057.                 'transaction_ok' => $transaction_ok,
  1058.                 'reservation' => $reservation,
  1059.                 'customer' => $customer,
  1060.                 'reservation_regle' => number_format($reservation_regle2','' ') . ' €',
  1061.                 'reservation_montant' => number_format($reservation_montant2','' ') . ' €',
  1062.                 'reservation_montant_tva' => number_format(($reservation_montant $reservation_montant_ht), 2','' ') . ' €',
  1063.                 'reservation_montant_ht' => number_format($reservation_montant_ht2','' ') . ' €',
  1064.                 // 'print_url' => '?idresa='.$reservation_number,
  1065.                 'failure_id' => $failure_id,
  1066.                 'page_url' => $pageUrl,
  1067.                 'error' => $error
  1068.             )
  1069.         );
  1070.     }
  1071.     private function addReservationDetail(array $args
  1072.     {
  1073.         $em $this->getDoctrine()->getManager();
  1074.         $reservationDetails = new ReservationDetails();
  1075.         $reservationDetails->setReservation($args['Reservation']);
  1076.         $reservationDetails->setDesignation($args['Designation']);
  1077.         $reservationDetails->setCodeActivity($args['CodeActivity']);
  1078.         $reservationDetails->setDate($args['Date']);
  1079.         $reservationDetails->setCreneau($args['Creneau']);
  1080.         $reservationDetails->setQuantity($args['Quantity']);
  1081.         $reservationDetails->setPuTTC($args['PuTTC']);
  1082.         $reservationDetails->setTauxTVA($args['TauxTVA']);
  1083.         $reservationDetails->setTotalHt($args['TotalHt']);
  1084.         $reservationDetails->setMontantTva($args['MontantTva']);
  1085.         $reservationDetails->setTotalTTC($args['TotalTTC']);
  1086.         $reservationDetails->setParent($args['Parent']);
  1087.         $em->persist($reservationDetails);
  1088.         $em->flush();
  1089.         return $reservationDetails;
  1090.     }
  1091.     private function sanitize_cart_details($cart_details
  1092.     {
  1093.         $return_cart_details $cart_details;
  1094.         foreach ($cart_details as $code_formule => $value_formule) {
  1095.             $return_cart_details[$code_formule]['obj_formule'] = $value_formule['obj_formule']->getID();
  1096.             foreach ($value_formule['forfaits'] as $key_forfait => $value_forfait) {
  1097.                 $return_cart_details[$code_formule]['forfaits'][$key_forfait]['obj_forfait'] = $value_forfait['obj_forfait']->getDesignation();
  1098.                 foreach ($value_forfait['tarifs'] as $key_tarif => $value_tarif) {
  1099.                     $return_cart_details[$code_formule]['forfaits'][$key_forfait]['tarifs'][$key_tarif]['obj_tarif'] = $value_tarif['obj_tarif']->getDesignation();
  1100.                 }
  1101.                 if(isset($value_forfait['options']) && $value_forfait['options']) {
  1102.                     foreach ($value_forfait['options'] as $key_option => $value_option) {
  1103.                         $return_cart_details[$code_formule]['forfaits'][$key_forfait]['options'][$key_option]['obj_option'] = $value_option['obj_option']->getDesignation();
  1104.                     }
  1105.                 }
  1106.                 if(isset($value_forfait['activity']) && $value_forfait['activity']) {
  1107.                     foreach ($value_forfait['activity'] as $key_activity => $value_activity) {
  1108.                         $return_cart_details[$code_formule]['forfaits'][$key_forfait]['activity'][$key_activity]['obj_activity'] = $value_activity['obj_activity']->getDesignation();
  1109.                     }
  1110.                 }
  1111.             }
  1112.         }
  1113.         return $return_cart_details;
  1114.     }
  1115. }