src/Controller/PanierController.php line 275

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Commande;
  4. use App\Entity\CommandeFormation;
  5. use App\Entity\FormationElearning;
  6. use App\Repository\CategorieElearningRepository;
  7. use App\Repository\CommandeFormationRepository;
  8. use App\Repository\CommandeRepository;
  9. use App\Repository\EmailsadminRepository;
  10. use App\Repository\FormationElearningRepository;
  11. use App\Repository\PackRepository;
  12. use App\Repository\SettingRepository;
  13. use App\Repository\UserRepository;
  14. use DateTime;
  15. use Dompdf\Dompdf;
  16. use Dompdf\Options;
  17. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. use Symfony\Component\Mailer\MailerInterface;
  25. use Symfony\Component\Mime\Address;
  26. use Symfony\Component\Mime\Email;
  27. use Symfony\Component\Routing\Annotation\Route;
  28. use Symfony\Component\Security\Core\Security;
  29. #[Route('/panier')]
  30. class PanierController extends AbstractController
  31. {
  32.     private $fromAddress;
  33.     public function __construct(
  34.         ParameterBagInterface $parameterBag  // Injection du service ParameterBagInterface
  35.     ) {
  36.         $this->fromAddress $parameterBag->get('mailer_from_address');
  37.     }
  38.     #[Route('/confirmer'name'panier_confirmer')]
  39.     public function confirmer(
  40.         SessionInterface $session,
  41.         FormationElearningRepository $formationElearningRepository,
  42.         Security $security,
  43.         CommandeRepository $commandeRepository,
  44.         CommandeFormationRepository $commandeFormationRepository,
  45.         SettingRepository $settingRepository,
  46.         MailerInterface $mailer,UserRepository $userRepository,
  47.         EmailsadminRepository $emailsadminRepository
  48.     ): Response {
  49.         $iduser $security->getUser()->getId();
  50. $userconecte$userRepository->find($iduser);
  51.         // 1. Vérifier l'utilisateur connecté
  52.         $user $security->getUser();
  53.         if (!$user) {
  54.             return $this->redirectToRoute('app_login');
  55.         }
  56.         // 2. Récupérer le panier
  57.         $panier $session->get('panier', []);
  58.         if (empty($panier)) {
  59.             $this->addFlash('warning''Votre panier est vide.');
  60.             return $this->redirectToRoute('panier_voir');
  61.         }
  62.         // 3. Calculer sous-total, tva et total
  63.         $sousTotal 0;
  64.         foreach ($panier as $formationId => $quantite) {
  65.             $formation $formationElearningRepository->find($formationId);
  66.             if ($formation) {
  67.                 $sousTotal += (float)$formation->getPrix() * $quantite;
  68.             }
  69.         }
  70.         $tva $sousTotal 0.19;
  71.         $timbre 1;
  72.         $total $sousTotal $tva $timbre;
  73.         // 4. Créer la commande
  74.         $commande = new Commande();
  75.         $commande->setUser($user);
  76.         $commande->setDate(new DateTime());
  77.         $commande->setSoustotal($sousTotal);
  78.         $commande->setTva($tva);
  79.         $commande->setTotal($total);
  80.         $commande->setIsVu(false);
  81.         $commande->setStatut('En attente');
  82.         $commande->setIsPayer(false);
  83.         // Persister la commande en base
  84.         $commandeRepository->save($commandetrue);
  85.         // 5. Créer CommandeFormation
  86.         foreach ($panier as $formationId => $quantite) {
  87.             $formation $formationElearningRepository->find($formationId);
  88.             if ($formation) {
  89.                 $commandeFormation = new CommandeFormation();
  90.                 $commandeFormation->setCommande($commande);
  91.                 $commandeFormation->setFormation($formation);
  92.                 $commandeFormationRepository->save($commandeFormationtrue);
  93.             }
  94.         }
  95.         $commandesFormation=$commandeFormationRepository->findBy(['commande'=>$commande]);
  96.         // 6. Générer le PDF directement ici (sans service)
  97.         // 6.a Options de DomPDF
  98.         $pdfOptions = new Options();
  99.         $pdfOptions->set('defaultFont''Arial');
  100. // Autorise le chargement d'images via des URLs absolues
  101.         $pdfOptions->setIsRemoteEnabled(true);
  102.         $dompdf = new Dompdf($pdfOptions);
  103.         // 6.c Générer le HTML via un template Twig
  104.         //    -> vous pouvez créer un template: templates/facture/facture.html.twig
  105.         $html $this->renderView('commande/facture.html.twig', [
  106.             'commande' => $commande,'commandesFormation'=>$commandesFormation,
  107.             'setting'=>$settingRepository->findOneBy(['id'=>1])
  108.         ]);
  109.         // 6.d Charger le HTML dans DomPDF
  110.         $dompdf->loadHtml($html);
  111.         // 6.e Définir la taille de page, orientation...
  112.         $dompdf->setPaper('A4''portrait');
  113.         // 6.f Générer le PDF
  114.         $dompdf->render();
  115.         // 6.g Nom du fichier, ex: facture-<id>.pdf
  116.         $fileName sprintf('BonCommande-%d.pdf'$commande->getId());
  117.         // 6.h Récupérer le répertoire d'upload défini dans services.yaml
  118.         $factureDirectory $this->getParameter('facture_directory');
  119.         $pdfFilePath $factureDirectory.'/'.$fileName;
  120.         // 6.i Sauvegarder le PDF sur le disque
  121.         file_put_contents($pdfFilePath$dompdf->output());
  122.         // 6.j (Optionnel) Enregistrer ce nom/chemin dans la commande si vous avez un champ 'facture'
  123.          $commande->setCommande($fileName);
  124.          $commandeRepository->save($commandetrue);
  125.         $tabadmin = array();
  126.         $admins $userRepository->findByRoleAdmin();
  127.         foreach ($admins as $a) {
  128.             array_push($tabadmin$a->getEmail());
  129.             $emailsadmin=$emailsadminRepository->findBy(['user'=>$a]);
  130.             foreach ($emailsadmin as $item) {
  131.                 if ($item->getEmail()) {
  132.                     array_push($tabadmin$item->getEmail());
  133.                 }
  134.             }
  135.         }
  136.         try{
  137.             $email = (new TemplatedEmail())
  138.                 ->from(new Address($this->fromAddress'Sip Academy'))  // Utilisation de Address pour inclure l'email et le nom
  139.               ->to($userconecte->getEmail())
  140.                 ->subject('Confirmation de votre commande SIP-ACADEMY')
  141.                 ->htmlTemplate(
  142.                     'formation_elearning/email.html.twig'
  143.                 )
  144.                 ->context([
  145.                     'setting'=>$settingRepository->find(1),
  146.                     'user'=>$userconecte,'commandesFormation'=>$commandesFormation,
  147.                     'commande'=>$commande
  148.                 ])
  149.             ->attachFromPath($pdfFilePath$fileName'application/pdf');
  150.             $mailer->send($email);
  151.             $emailAdmin = (new TemplatedEmail())
  152.                 ->from(new Address($this->fromAddress'Sip Academy'))
  153.                 ->to(...$tabadmin)
  154.                 ->subject('Nouvelle commande reçue - SIP Academy')
  155.                 ->htmlTemplate('formation_elearning/emailadmin.html.twig')
  156.                 ->context([
  157.                     'setting' => $settingRepository->find(1),
  158.                     'user' => $commande->getUser(),
  159.                     'commandesFormation' => $commandesFormation,
  160.                     'commande' => $commande
  161.                 ])
  162.                 ->attachFromPath($pdfFilePath$fileName'application/pdf');
  163.             $mailer->send($emailAdmin);
  164.         }
  165.         catch (\Exception $e) {
  166.             // 7. Vider le panier
  167.             $session->remove('panier');
  168.             // 8. Flash message
  169.           //  $this->addFlash('success', 'Votre commande est confirmée ! Un administrateur vous contactera prochainement.');
  170.             // 9. Redirection
  171.             return $this->redirectToRoute('app_panier_commandesuccess');
  172.         }
  173.         // 7. Vider le panier
  174.         $session->remove('panier');
  175.         // 8. Flash message
  176.      //   $this->addFlash('success', 'Votre commande est confirmée ! Un administrateur vous contactera prochainement.');
  177.         // 9. Redirection
  178.         return $this->redirectToRoute('app_panier_commandesuccess');
  179.     }
  180.     #[Route('/modifier/{id}/{quantite}'name'panier_modifier'methods: ['POST'])]
  181.     public function modifierQuantite($id$quantiteSessionInterface $session): JsonResponse
  182.     {
  183.         $panier $session->get('panier', []);
  184.         if (!empty($panier[$id])) {
  185.             $panier[$id] = (int)$quantite;
  186.             if ($panier[$id] <= 0) {
  187.                 unset($panier[$id]);
  188.             }
  189.             $session->set('panier'$panier);
  190.         }
  191.         return $this->json(['status' => 'ok']);
  192.     }
  193.     #[Route('/supprimer/{id}'name'panier_supprimer'methods: ['POST'])]
  194.     public function supprimerFormation($idSessionInterface $session): JsonResponse
  195.     {
  196.         $panier $session->get('panier', []);
  197.         if (!empty($panier[$id])) {
  198.             unset($panier[$id]);
  199.             $session->set('panier'$panier);
  200.         }
  201.         return $this->json(['status' => 'ok']);
  202.     }
  203.     #[Route('/voir'name'panier_voir')]
  204.     public function voirPanier(
  205.         CategorieElearningRepository $categorieElearningRepository,
  206.         SettingRepository $settingRepository,
  207.         SessionInterface $session,
  208.         FormationElearningRepository $formationRepository,
  209.         PackRepository $packRepository,
  210.         Request $request
  211.     ): Response
  212.     {
  213.         // Récupérer les deux paniers
  214.         $panierFormations $session->get('panier', []);
  215.         $panierPacks $session->get('panier_packs', []);
  216.         $formations = [];
  217.         $packs = [];
  218.         // Traiter les formations
  219.         foreach ($panierFormations as $id => $quantite) {
  220.             $formation $formationRepository->find($id);
  221.             if ($formation) {
  222.                 $formations[] = [
  223.                     'item' => $formation,
  224.                     'quantite' => $quantite,
  225.                     'prix' => (float)$formation->getPrix(),
  226.                     'type' => 'formation'
  227.                 ];
  228.             }
  229.         }
  230.         // Traiter les packs
  231.         foreach ($panierPacks as $id => $quantite) {
  232.             $pack $packRepository->find($id);
  233.             if ($pack) {
  234.                 $packs[] = [
  235.                     'item' => $pack,
  236.                     'quantite' => $quantite,
  237.                     'prix' => (float)$pack->getPrix(),
  238.                     'type' => 'pack'
  239.                 ];
  240.             }
  241.         }
  242.         // Combiner tous les éléments
  243.         $items array_merge($formations$packs);
  244.         $isAuthenticated $this->isGranted('IS_AUTHENTICATED_FULLY');
  245.         return $this->render('panier/index.html.twig', [
  246.             'items' => $items,
  247.             'setting' => $settingRepository->find(1),
  248.             'categories' => $categorieElearningRepository->findAll(),
  249.             'isAuthenticated' => $isAuthenticated
  250.         ]);
  251.     }
  252.     #[Route('/ajouter/{id}'name'panier_ajouter'methods: ['POST'])]
  253.     public function ajouter(
  254.         $id,
  255.         Request $request,
  256.         SessionInterface $session,
  257.         FormationElearningRepository $formationRepository,
  258.         PackRepository $packRepository
  259.     ): JsonResponse {
  260.         $type $request->query->get('type''formation'); // 'formation' ou 'pack'
  261.         if ($type === 'formation') {
  262.             $item $formationRepository->find($id);
  263.             $sessionKey 'panier';
  264.             $itemName 'Formation';
  265.         } else {
  266.             $item $packRepository->find($id);
  267.             $sessionKey 'panier_packs';
  268.             $itemName 'Pack';
  269.         }
  270.         if (!$item) {
  271.             return $this->json(['status' => 'error''message' => $itemName ' introuvable'], 404);
  272.         }
  273.         $panier $session->get($sessionKey, []);
  274.         // Si l'élément est déjà dans le panier, on ne l'ajoute pas
  275.         if (!empty($panier[$id])) {
  276.             return $this->json([
  277.                 'status' => 'already_in_cart',
  278.                 'total_items' => $this->getTotalItems($session),
  279.                 'message' => $itemName ' déjà ajouté(e) au panier !',
  280.             ]);
  281.         }
  282.         // Sinon, on ajoute avec quantité = 1
  283.         $panier[$id] = 1;
  284.         $session->set($sessionKey$panier);
  285.         return $this->json([
  286.             'status' => 'ok',
  287.             'quantite' => 1,
  288.             'total_items' => $this->getTotalItems($session),
  289.             'message' => $itemName ' ajouté(e) au panier avec succès !'
  290.         ]);
  291.     }
  292. // Méthode pour calculer le total des items dans le panier
  293.     private function getTotalItems(SessionInterface $session): int
  294.     {
  295.         $panierFormations $session->get('panier', []);
  296.         $panierPacks $session->get('panier_packs', []);
  297.         return array_sum($panierFormations) + array_sum($panierPacks);
  298.     }
  299. //    #[Route('/ajouter/{id}', name: 'panier_ajouter', methods: ['POST'])]
  300. //    public function ajouter($id, SessionInterface $session, FormationElearningRepository $formationRepository): JsonResponse
  301. //    {
  302. //        $formation = $formationRepository->find($id);
  303. //        if (!$formation) {
  304. //            return $this->json(['status' => 'error', 'message' => 'Formation introuvable'], 404);
  305. //        }
  306. //
  307. //        $panier = $session->get('panier', []);
  308. //
  309. //        if (!empty($panier[$id])) {
  310. //            $panier[$id]++;
  311. //        } else {
  312. //            $panier[$id] = 1;
  313. //        }
  314. //
  315. //        $session->set('panier', $panier);
  316. //
  317. //        return $this->json([
  318. //            'status' => 'ok',
  319. //            'quantite' => $panier[$id],
  320. //            'total_items' => array_sum($panier),
  321. //        ]);
  322. //    }
  323.     #[Route('/panier'name'app_panier')]
  324.     public function index(): Response
  325.     {
  326.         return $this->render('panier/index.html.twig', [
  327.             'controller_name' => 'PanierController',
  328.         ]);
  329.     }
  330.     #[Route('/commande-success'name'app_panier_commandesuccess')]
  331.     public function test(CategorieElearningRepository $categorieElearningRepository,SettingRepository $settingRepository): Response
  332.     {
  333.         return $this->render('panier/commandesuccess.html.twig', [
  334.             'controller_name' => 'PanierController',
  335.             'setting' => $settingRepository->find(1),
  336.             'categories' => $categorieElearningRepository->findAll(),
  337.         ]);
  338.     }
  339. }