<?php
namespace App\Controller;
use App\Entity\Commande;
use App\Entity\CommandeFormation;
use App\Entity\FormationElearning;
use App\Repository\CategorieElearningRepository;
use App\Repository\CommandeFormationRepository;
use App\Repository\CommandeRepository;
use App\Repository\EmailsadminRepository;
use App\Repository\FormationElearningRepository;
use App\Repository\PackRepository;
use App\Repository\SettingRepository;
use App\Repository\UserRepository;
use DateTime;
use Dompdf\Dompdf;
use Dompdf\Options;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
#[Route('/panier')]
class PanierController extends AbstractController
{
private $fromAddress;
public function __construct(
ParameterBagInterface $parameterBag // Injection du service ParameterBagInterface
) {
$this->fromAddress = $parameterBag->get('mailer_from_address');
}
#[Route('/confirmer', name: 'panier_confirmer')]
public function confirmer(
SessionInterface $session,
FormationElearningRepository $formationElearningRepository,
Security $security,
CommandeRepository $commandeRepository,
CommandeFormationRepository $commandeFormationRepository,
SettingRepository $settingRepository,
MailerInterface $mailer,UserRepository $userRepository,
EmailsadminRepository $emailsadminRepository
): Response {
$iduser = $security->getUser()->getId();
$userconecte= $userRepository->find($iduser);
// 1. Vérifier l'utilisateur connecté
$user = $security->getUser();
if (!$user) {
return $this->redirectToRoute('app_login');
}
// 2. Récupérer le panier
$panier = $session->get('panier', []);
if (empty($panier)) {
$this->addFlash('warning', 'Votre panier est vide.');
return $this->redirectToRoute('panier_voir');
}
// 3. Calculer sous-total, tva et total
$sousTotal = 0;
foreach ($panier as $formationId => $quantite) {
$formation = $formationElearningRepository->find($formationId);
if ($formation) {
$sousTotal += (float)$formation->getPrix() * $quantite;
}
}
$tva = $sousTotal * 0.19;
$timbre = 1;
$total = $sousTotal + $tva + $timbre;
// 4. Créer la commande
$commande = new Commande();
$commande->setUser($user);
$commande->setDate(new DateTime());
$commande->setSoustotal($sousTotal);
$commande->setTva($tva);
$commande->setTotal($total);
$commande->setIsVu(false);
$commande->setStatut('En attente');
$commande->setIsPayer(false);
// Persister la commande en base
$commandeRepository->save($commande, true);
// 5. Créer CommandeFormation
foreach ($panier as $formationId => $quantite) {
$formation = $formationElearningRepository->find($formationId);
if ($formation) {
$commandeFormation = new CommandeFormation();
$commandeFormation->setCommande($commande);
$commandeFormation->setFormation($formation);
$commandeFormationRepository->save($commandeFormation, true);
}
}
$commandesFormation=$commandeFormationRepository->findBy(['commande'=>$commande]);
// 6. Générer le PDF directement ici (sans service)
// 6.a Options de DomPDF
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
// Autorise le chargement d'images via des URLs absolues
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
// 6.c Générer le HTML via un template Twig
// -> vous pouvez créer un template: templates/facture/facture.html.twig
$html = $this->renderView('commande/facture.html.twig', [
'commande' => $commande,'commandesFormation'=>$commandesFormation,
'setting'=>$settingRepository->findOneBy(['id'=>1])
]);
// 6.d Charger le HTML dans DomPDF
$dompdf->loadHtml($html);
// 6.e Définir la taille de page, orientation...
$dompdf->setPaper('A4', 'portrait');
// 6.f Générer le PDF
$dompdf->render();
// 6.g Nom du fichier, ex: facture-<id>.pdf
$fileName = sprintf('BonCommande-%d.pdf', $commande->getId());
// 6.h Récupérer le répertoire d'upload défini dans services.yaml
$factureDirectory = $this->getParameter('facture_directory');
$pdfFilePath = $factureDirectory.'/'.$fileName;
// 6.i Sauvegarder le PDF sur le disque
file_put_contents($pdfFilePath, $dompdf->output());
// 6.j (Optionnel) Enregistrer ce nom/chemin dans la commande si vous avez un champ 'facture'
$commande->setCommande($fileName);
$commandeRepository->save($commande, true);
$tabadmin = array();
$admins = $userRepository->findByRoleAdmin();
foreach ($admins as $a) {
array_push($tabadmin, $a->getEmail());
$emailsadmin=$emailsadminRepository->findBy(['user'=>$a]);
foreach ($emailsadmin as $item) {
if ($item->getEmail()) {
array_push($tabadmin, $item->getEmail());
}
}
}
try{
$email = (new TemplatedEmail())
->from(new Address($this->fromAddress, 'Sip Academy')) // Utilisation de Address pour inclure l'email et le nom
->to($userconecte->getEmail())
->subject('Confirmation de votre commande SIP-ACADEMY')
->htmlTemplate(
'formation_elearning/email.html.twig'
)
->context([
'setting'=>$settingRepository->find(1),
'user'=>$userconecte,'commandesFormation'=>$commandesFormation,
'commande'=>$commande
])
->attachFromPath($pdfFilePath, $fileName, 'application/pdf');
$mailer->send($email);
$emailAdmin = (new TemplatedEmail())
->from(new Address($this->fromAddress, 'Sip Academy'))
->to(...$tabadmin)
->subject('Nouvelle commande reçue - SIP Academy')
->htmlTemplate('formation_elearning/emailadmin.html.twig')
->context([
'setting' => $settingRepository->find(1),
'user' => $commande->getUser(),
'commandesFormation' => $commandesFormation,
'commande' => $commande
])
->attachFromPath($pdfFilePath, $fileName, 'application/pdf');
$mailer->send($emailAdmin);
}
catch (\Exception $e) {
// 7. Vider le panier
$session->remove('panier');
// 8. Flash message
// $this->addFlash('success', 'Votre commande est confirmée ! Un administrateur vous contactera prochainement.');
// 9. Redirection
return $this->redirectToRoute('app_panier_commandesuccess');
}
// 7. Vider le panier
$session->remove('panier');
// 8. Flash message
// $this->addFlash('success', 'Votre commande est confirmée ! Un administrateur vous contactera prochainement.');
// 9. Redirection
return $this->redirectToRoute('app_panier_commandesuccess');
}
#[Route('/modifier/{id}/{quantite}', name: 'panier_modifier', methods: ['POST'])]
public function modifierQuantite($id, $quantite, SessionInterface $session): JsonResponse
{
$panier = $session->get('panier', []);
if (!empty($panier[$id])) {
$panier[$id] = (int)$quantite;
if ($panier[$id] <= 0) {
unset($panier[$id]);
}
$session->set('panier', $panier);
}
return $this->json(['status' => 'ok']);
}
#[Route('/supprimer/{id}', name: 'panier_supprimer', methods: ['POST'])]
public function supprimerFormation($id, SessionInterface $session): JsonResponse
{
$panier = $session->get('panier', []);
if (!empty($panier[$id])) {
unset($panier[$id]);
$session->set('panier', $panier);
}
return $this->json(['status' => 'ok']);
}
#[Route('/voir', name: 'panier_voir')]
public function voirPanier(
CategorieElearningRepository $categorieElearningRepository,
SettingRepository $settingRepository,
SessionInterface $session,
FormationElearningRepository $formationRepository,
PackRepository $packRepository,
Request $request
): Response
{
// Récupérer les deux paniers
$panierFormations = $session->get('panier', []);
$panierPacks = $session->get('panier_packs', []);
$formations = [];
$packs = [];
// Traiter les formations
foreach ($panierFormations as $id => $quantite) {
$formation = $formationRepository->find($id);
if ($formation) {
$formations[] = [
'item' => $formation,
'quantite' => $quantite,
'prix' => (float)$formation->getPrix(),
'type' => 'formation'
];
}
}
// Traiter les packs
foreach ($panierPacks as $id => $quantite) {
$pack = $packRepository->find($id);
if ($pack) {
$packs[] = [
'item' => $pack,
'quantite' => $quantite,
'prix' => (float)$pack->getPrix(),
'type' => 'pack'
];
}
}
// Combiner tous les éléments
$items = array_merge($formations, $packs);
$isAuthenticated = $this->isGranted('IS_AUTHENTICATED_FULLY');
return $this->render('panier/index.html.twig', [
'items' => $items,
'setting' => $settingRepository->find(1),
'categories' => $categorieElearningRepository->findAll(),
'isAuthenticated' => $isAuthenticated
]);
}
#[Route('/ajouter/{id}', name: 'panier_ajouter', methods: ['POST'])]
public function ajouter(
$id,
Request $request,
SessionInterface $session,
FormationElearningRepository $formationRepository,
PackRepository $packRepository
): JsonResponse {
$type = $request->query->get('type', 'formation'); // 'formation' ou 'pack'
if ($type === 'formation') {
$item = $formationRepository->find($id);
$sessionKey = 'panier';
$itemName = 'Formation';
} else {
$item = $packRepository->find($id);
$sessionKey = 'panier_packs';
$itemName = 'Pack';
}
if (!$item) {
return $this->json(['status' => 'error', 'message' => $itemName . ' introuvable'], 404);
}
$panier = $session->get($sessionKey, []);
// Si l'élément est déjà dans le panier, on ne l'ajoute pas
if (!empty($panier[$id])) {
return $this->json([
'status' => 'already_in_cart',
'total_items' => $this->getTotalItems($session),
'message' => $itemName . ' déjà ajouté(e) au panier !',
]);
}
// Sinon, on ajoute avec quantité = 1
$panier[$id] = 1;
$session->set($sessionKey, $panier);
return $this->json([
'status' => 'ok',
'quantite' => 1,
'total_items' => $this->getTotalItems($session),
'message' => $itemName . ' ajouté(e) au panier avec succès !'
]);
}
// Méthode pour calculer le total des items dans le panier
private function getTotalItems(SessionInterface $session): int
{
$panierFormations = $session->get('panier', []);
$panierPacks = $session->get('panier_packs', []);
return array_sum($panierFormations) + array_sum($panierPacks);
}
// #[Route('/ajouter/{id}', name: 'panier_ajouter', methods: ['POST'])]
// public function ajouter($id, SessionInterface $session, FormationElearningRepository $formationRepository): JsonResponse
// {
// $formation = $formationRepository->find($id);
// if (!$formation) {
// return $this->json(['status' => 'error', 'message' => 'Formation introuvable'], 404);
// }
//
// $panier = $session->get('panier', []);
//
// if (!empty($panier[$id])) {
// $panier[$id]++;
// } else {
// $panier[$id] = 1;
// }
//
// $session->set('panier', $panier);
//
// return $this->json([
// 'status' => 'ok',
// 'quantite' => $panier[$id],
// 'total_items' => array_sum($panier),
// ]);
// }
#[Route('/panier', name: 'app_panier')]
public function index(): Response
{
return $this->render('panier/index.html.twig', [
'controller_name' => 'PanierController',
]);
}
#[Route('/commande-success', name: 'app_panier_commandesuccess')]
public function test(CategorieElearningRepository $categorieElearningRepository,SettingRepository $settingRepository): Response
{
return $this->render('panier/commandesuccess.html.twig', [
'controller_name' => 'PanierController',
'setting' => $settingRepository->find(1),
'categories' => $categorieElearningRepository->findAll(),
]);
}
}