<?php
namespace App\Controller;
use App\Dto\CommandeKitRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\TrPanier;
use App\Form\TrPanierType;
use App\Repository\TrPanierRepository;
use App\Repository\TrCoeurRepository;
use App\Entity\TrCoeur;
use App\Entity\KitPromotionnel;
use App\Entity\TrClient;
use App\Exception\CommandeKitNotFoundException;
use App\Exception\CommandeKitValidationException;
use App\Entity\TrProduits;
use App\Form\TrProduitsType;
use App\Repository\TrProduitsRepository;
use App\Service\Cart\CartService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use symfony\component\Form\FormBuilderInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\DependencyInjection\Loader\Configurator\form;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Psr\Log\LoggerInterface;
use App\Service\CommandeKitService;
class TrPanierController extends AbstractController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @Route("/tr/panier", name="TrPanier_news")
* @Route("/tr/panier/{id}/edit", name="TrPanier_modification")
*/
public function form(TrPanier $Panier = null, request $request, EntityManagerInterface $manager, SessionInterface $session, SluggerInterface $slugger)
{
if (!$Panier) {
$Panier = new TrPanier();
}
$form = $this->createForm(TrPanierType::class, $Panier);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$manager->persist($Panier);
$manager->flush();
/**@var FlashBag */
$flashBag = $session->getBag('flashes');
$flashBag->add('success', "Action effectuée avec succès!");
return $this->redirectToRoute('TrPanier_afficher');
}
$title = "Créer un Panier";
$Soustitle = "Liste des Paniers";
$Nom_Table = "Les Paniers";
$Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
$Titre_Principal = "Paniers";
return $this->render('tr_panier/Panier.html.twig', [
'form' => $form->createView(),
'edit' => $Panier->getId() !== null,
'title' => $title,
'Soustitle' => $Soustitle,
'Nom_Table' => $Nom_Table,
'Explication_Nom_Table' => $Explication_Nom_Table,
'Active_href' => 'Active_Panier',
'Parametre' => 'Parametre_metier',
'Titre_Principal' => $Titre_Principal,
]);
}
/* Supprimer*/
/**
* @Route("/tr/panier/{id}/delete", name="TrPanier_delete")
*/
public function supprimer(TrPanier $Panier, request $request, EntityManagerInterface $manager, SessionInterface $session)
{
$donnees = $this->getDoctrine()->getManager();
$donnees->remove($Panier);
$donnees->flush();
/**@var FlashBag */
$flashBag = $session->getBag('flashes');
$flashBag->add('success', "Action effectuée avec succès!");
return $this->redirectToRoute('TrPanier_afficher');
}
/* Affichage*/
/**
* @Route("/tr/panier/affichage", name="TrPanier_afficher")
*/
public function afficher(EntityManagerInterface $manager, request $request)
{
$title = "Affichage des Paniers";
$repository = $manager->getRepository(TrPanier::class);
$Paniers = $repository->findAll();
$title = "Créer un Panier";
$Soustitle = "Liste des Paniers";
$Nom_Table = "Les Paniers";
$Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
$Titre_Principal = "Paniers";
return $this->render('tr_panier/index.html.twig', [
'Paniers' => $Paniers,
'title' => $title,
'Soustitle' => $Soustitle,
'Nom_Table' => $Nom_Table,
'Explication_Nom_Table' => $Explication_Nom_Table,
'Active_href' => 'Active_Panier',
'Parametre' => 'Parametre_metier',
'Titre_Principal' => $Titre_Principal,
]);
}
/**
* @Route("/tr/panier/Ajout/{id}", name="TrPanier_add")
*/
public function Add($id, CartService $cartService)
{
$cartService->add($id);
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/Addition/{id}", name="TrPanier_Addition")
*/
public function Addition($id, CartService $cartService)
{
$cartService->add($id);
return $this->redirectToRoute('Bussness');
}
/**
* @Route("/tr/panier/subtraction/{id}", name="TrPanier_subtraction")
*/
public function subtraction($id, CartService $cartService)
{
$cartService->subtraction($id);
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/Initial", name="panier_index")
*/
public function index(CartService $cartService)
{
$title = "Créer un Panier";
$Soustitle = "Liste des Paniers";
$Nom_Table = "Les Paniers";
$Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
$Titre_Principal = "Paniers";
return $this->render('bussness/Panier.html.twig', [
'items' => $cartService->getFullCart(),
'kitItems' => $cartService->getFullKitCart(),
'Nombre_items' => $cartService->getQuantite(),
'productTotal' => $cartService->getProductsTotal(),
'kitTotal' => $cartService->getKitsTotal(),
'title' => $title,
'Soustitle' => $Soustitle,
'Nom_Table' => $Nom_Table,
'Explication_Nom_Table' => $Explication_Nom_Table,
'Titre_Principal' => $Titre_Principal,
'total' => $cartService->getTotal(),
'quantite' => $cartService->getQuantite(),
'totalcoeur' => count($cartService->getCoeur()),
'google_maps_api_key' => $this->getParameter('google_maps_api_key'),
]);
}
/**
* @Route("/tr/panier/remove/{id}", name="panier_remove")
*/
public function remove($id, CartService $cartService)
{
$cartService->remove($id);
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/kits/add/{id}", name="TrPanierKit_add")
*/
public function addKit($id, CartService $cartService, SessionInterface $session): Response
{
if (!$cartService->addKit((int) $id)) {
$session->getBag('flashes')->add('danger', 'Ce kit n est plus disponible.');
} else {
$session->getBag('flashes')->add('success', 'Kit promotionnel ajoute au panier.');
}
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/kits/addition/{id}", name="TrPanierKit_Addition")
*/
public function addKitFromFront($id, CartService $cartService, Request $request, SessionInterface $session): Response
{
if (!$cartService->addKit((int) $id)) {
$session->getBag('flashes')->add('danger', 'Ce kit n est plus disponible.');
} else {
$session->getBag('flashes')->add('success', 'Kit promotionnel ajoute au panier.');
}
$referer = $request->headers->get('referer');
if ($referer) {
return $this->redirect($referer);
}
return $this->redirectToRoute('Bussness');
}
/**
* @Route("/tr/panier/kits/subtraction/{id}", name="TrPanierKit_subtraction")
*/
public function subtractionKit($id, CartService $cartService): Response
{
$cartService->subtractionKit((int) $id);
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/kits/remove/{id}", name="TrPanierKit_remove")
*/
public function removeKit($id, CartService $cartService): Response
{
$cartService->removeKit((int) $id);
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/tr/panier/kits/interet", name="TrPanierKit_interest", methods={"POST"})
*/
public function registerKitInterest(
Request $request,
CartService $cartService,
SessionInterface $session,
CommandeKitService $commandeKitService,
EntityManagerInterface $entityManager
): Response
{
$kitItems = $cartService->getFullKitCart();
if (0 === count($kitItems)) {
$session->getBag('flashes')->add('danger', 'Aucun kit disponible dans votre panier.');
return $this->redirectToRoute('panier_index');
}
$errors = $cartService->validateKitCart();
if ([] !== $errors) {
foreach ($errors as $error) {
$session->getBag('flashes')->add('danger', $error);
}
return $this->redirectToRoute('panier_index');
}
$contactName = trim((string) $request->request->get('contact_name'));
$contactPhone = trim((string) $request->request->get('contact_phone'));
$commentaire = trim((string) $request->request->get('commentaire'));
if ($this->getUser()) {
if ('' === $contactName) {
$contactName = method_exists($this->getUser(), 'getFulName') ? (string) $this->getUser()->getFulName() : $contactName;
}
if ('' === $contactPhone && method_exists($this->getUser(), 'getEmail')) {
$client = $entityManager->getRepository(TrClient::class)->findOneBy([
'email' => (string) $this->getUser()->getEmail(),
]);
if ($client instanceof TrClient && null !== $client->getTelephone()) {
$contactPhone = trim((string) $client->getTelephone());
}
}
}
if ('' === $contactName || '' === $contactPhone) {
$session->getBag('flashes')->add('danger', 'Nom et telephone sont obligatoires pour demander un kit.');
return $this->redirectToRoute('panier_index');
}
$payload = [];
$createdCommandIds = [];
foreach ($kitItems as $item) {
$payload[] = [
'kit_id' => $item['kit']->getId(),
'kit_nom' => $item['kit']->getNom(),
'prix_kit' => $item['kit']->getPrixKit(),
'quantite' => $item['quantity'],
'items' => array_map(static function ($kitItem) {
return [
'produit' => null !== $kitItem->getProduit() ? $kitItem->getProduit()->getLIBELLE() : null,
'quantite' => $kitItem->getQuantite(),
];
}, $item['kit']->getItems()->toArray()),
];
try {
$commandeKit = $commandeKitService->createFromRequest(CommandeKitRequest::fromArray([
'kit_id' => $item['kit']->getId(),
'telephone' => $contactPhone,
'nom' => $contactName,
'quantite' => (int) $item['quantity'],
'commentaire' => $commentaire,
]));
$createdCommandIds[] = $commandeKit->getId();
} catch (CommandeKitNotFoundException $e) {
$this->logger->warning('Kit introuvable lors de l enregistrement depuis le panier.', [
'kit_id' => $item['kit']->getId(),
'error' => $e->getMessage(),
]);
$session->getBag('flashes')->add('danger', 'Un des kits selectionnes n est plus disponible.');
return $this->redirectToRoute('panier_index');
} catch (CommandeKitValidationException $e) {
$this->logger->warning('Validation bloquante lors de l enregistrement d une commande kit.', [
'kit_id' => $item['kit']->getId(),
'errors' => $e->getErrors(),
]);
$session->getBag('flashes')->add('danger', 'La demande de kit n a pas pu etre enregistree. Verifiez les informations saisies.');
return $this->redirectToRoute('panier_index');
} catch (\Throwable $e) {
$this->logger->error('Erreur technique lors de l enregistrement d une demande de kit depuis le panier.', [
'kit_id' => $item['kit']->getId(),
'error' => $e->getMessage(),
]);
$session->getBag('flashes')->add('danger', 'Une erreur technique est survenue lors de l enregistrement de votre demande de kit.');
return $this->redirectToRoute('panier_index');
}
}
$this->logger->info('Demandes de kits promotionnels enregistrees depuis le panier.', [
'customer_name' => $contactName,
'customer_phone' => $contactPhone,
'customer_email' => $this->getUser() && method_exists($this->getUser(), 'getEmail') ? $this->getUser()->getEmail() : null,
'commentaire' => $commentaire,
'kits' => $payload,
'commande_ids' => $createdCommandIds,
]);
$cartService->clearKitCart();
$session->getBag('flashes')->add('success', 'Votre demande pour les kits a bien ete enregistree. Notre equipe vous contactera.');
return $this->redirectToRoute('panier_index');
}
}