<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\CategoriesRepository;
use App\Repository\AlertesRepository;
use App\Repository\AnnoncesRepository;
use App\Repository\FavorisRepository;
use App\Repository\PaysRepository;
use App\Repository\VillesRepository;
use App\Repository\UserRepository;
use App\Repository\CommandesRepository;
use App\Repository\FacturesRepository;
use App\Repository\NotesEnseignesRepository;
use App\Repository\NotesAnnoncesRepository;
use App\Entity\Commandes;
use App\Entity\Factures;
use App\Entity\Alertes;
use App\Entity\Villes;
use App\Entity\Categories;
use Datetime;
use Symfony\Component\HttpFoundation\JsonResponse;
use Spipu\Html2Pdf\Html2Pdf;
use App\Entity\Favoris;
use Stripe\Stripe;
use Symfony\Component\HttpFoundation\Request;
use Knp\Component\Pager\PaginatorInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Entity\User;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use DansMaCulotte\Monetico\Monetico;
use DansMaCulotte\Monetico\Requests\PurchaseRequest;
use DansMaCulotte\Monetico\Resources\BillingAddressResource;
use DansMaCulotte\Monetico\Resources\ShippingAddressResource;
use DansMaCulotte\Monetico\Resources\ClientResource;
class DefaultController extends AbstractController
{
private $entityManager;
private $stripeSecretKey;
public function __construct(EntityManagerInterface $entityManager,string $stripeSecretKey)
{
$this->entityManager = $entityManager;
$this->stripeSecretKey = $stripeSecretKey;
}
/**
* @Route("/loginPopup", name="custom_login")
*/
public function loginPopup(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$referer = $request->headers->get('referer');
if ($this->getUser()) {
return $this->redirectToRoute(' ');
}
if ($request->isMethod('POST')) {
$email = $request->request->get('email');
$password = $request->request->get('password');
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $email]);
if (!$user) {
throw new AuthenticationException('Adresse e-mail ou mot de passe incorrect.');
}
$isPasswordValid = $passwordEncoder->isPasswordValid($user, $password);
if (!$isPasswordValid) {
throw new AuthenticationException('Adresse e-mail ou mot de passe incorrect.');
}
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
return $this->redirect($referer);
}
}
/**
* @Route("/", name="app_default")
*/
public function index(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$session->set('type', 'part');
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/index.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/gestion-des-cookies", name="app_cookie")
*/
public function cookie(AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/cookie.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/mentions-legales", name="app_mention")
*/
public function mention(AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/mention.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/protection-des-donnees", name="app_protection")
*/
public function protection(AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/protection.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/professionnels", name="professionnels")
*/
public function professionnels(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$session->set('type', 'pro');
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/indexPro.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/achatCredit", name="achatCredit")
*/
public function achatCredit(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/achatCredit.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/achatRecap", name="achatRecap")
*/
public function achatRecap(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$qt = $request->request->get('quantite');
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/achatRecap.html.twig', [
'qt' => $qt,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/paiementStripeForm", name="paiementStripeForm")
*/
public function paiementStripeForm(Request $request, CommandesRepository $commandesRepo, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$uniq = uniqid();
$session = $request->getSession();
$session->set('orderIdTemp', $uniq);
$user = $this->getUser();
$qt = $request->request->get('qt');
$total = $qt;
$commandes = new Commandes();
$commandes->setCreated(new DateTime());
$commandes->setQuantite($qt);
$commandes->setTotal($total);
$commandes->setUser($user);
$commandes->setUniqId($uniq);
$commandesRepo->add($commandes, true);
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/paiement.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/stripe", name="stripe")
*/
public function stripe(Request $request, CommandesRepository $commandesRepo, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$uniq = $session->get('orderIdTemp');
$commandes = $commandesRepo->findOneBy(array('UniqId'=>$uniq));
$total = $commandes->getTotal() * 100;
$description = 'commande numéro '.$commandes->getId();
$token = json_decode($request->getContent(), true)['token'];
Stripe::setApiKey($this->stripeSecretKey);
try {
$charge = \Stripe\Charge::create([
'amount' => $total,
'currency' => 'eur',
'source' => $token,
'description' => $description,
]);
return $this->json(['message' => 'Paiement effectué avec succès']);
} catch (CardException $e) {
return $this->json(['error' => $e->getMessage()], Response::HTTP_BAD_REQUEST);
} catch (ApiErrorException $e) {
return $this->json(['error' => 'Une erreur est survenue lors du traitement du paiement. Veuillez réessayer.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* @Route("/retourStripe/{etat}", name="retourStripe")
*/
public function retourStripe(Request $request, $etat, CommandesRepository $commandesRepo, FacturesRepository $facturesRepo, UserRepository $userRepo, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$uniq = $session->get('orderIdTemp');
$commandes = $commandesRepo->findOneBy(array('UniqId'=>$uniq));
if($etat == 'success') {
if(!$commandes->isPaye()) {
$commandes->setPaye(1);
$commandesRepo->add($commandes, true);
$user = $this->getUser();
$credit = $user->getCredits() + $commandes->getQuantite();
$user->setCredits($credit);
$userRepo->add($user, true);
$factureNew = new Factures();
$factureNew->setCreated(new DateTime());
$factureNew->setCommandes($commandes);
$factureNew->setUser($user);
$facturesRepo->add($factureNew, true);
$template = $this->renderView('default/facturesPdf.html.twig', [
'facture' => $factureNew
]);
$numero = date('Y').$factureNew->getId();
$html2pdf = new Html2Pdf();
$html2pdf->writeHTML($template);
$html2pdf->output('/var/www/vhosts/modixom.fr/httpdocs/public/factures/' . $numero . '.pdf', 'F');
}
}
$alertes = $alertesRepository->findBy(['User' => $this->getUser()]);
$categories = $categoriesRepository->findAll();
return $this->render('default/retourStripe.html.twig', [
'etat' => $etat,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/testpdf", name="testpdf")
*/
public function testpdf(Request $request, FacturesRepository $facturesRepo, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$facture = $facturesRepo->findOneById(1);
$template = $this->renderView('default/facturesPdf.html.twig', [
'facture' => $facture
]);
$html2pdf = new Html2Pdf();
$html2pdf->writeHTML($template);
$html2pdf->output('test.pdf');
}
/**
* @Route("/achatGenerationFacture", name="achatGenerationFacture")
*/
public function achatGenerationFacture(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/achatGenerationFacture.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/annonces", name="annonces")
*/
public function annonces(CategoriesRepository $categoriesRepository, FavorisRepository $favorisRepository, Request $request, AnnoncesRepository $annoncesRepository, VillesRepository $villesRepository, PaginatorInterface $paginator, NotesEnseignesRepository $notesEnseignesRepository, AlertesRepository $alertesRepository): Response
{
$categoriesSearch = '';
$citiesRes = '';
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
if (isset($_GET['tri'])) {
$triSearch = $_GET['tri'];
} else {
$triSearch = '';
}
if (isset($_GET['nbParPage'])) {
$nbParPage = $_GET['nbParPage'];
} else {
$nbParPage = 25;
}
if (isset($_GET['pro'])) {
$pro = $_GET['pro'];
} else {
$pro = 0;
}
if (isset($_GET['motscles'])) {
$motscles = $_GET['motscles'];
} else {
$motscles = '';
}
$villes = array();
$citiesRes = array();
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->getUser();
$favorisUser = array();
if (empty($session->get('type'))) {
$session->set('type', 'part');
}
if ($user) {
$session->set('type', $user->getType());
$favoris = $favorisRepository->findBy(array('User'=>$user));
foreach($favoris as $res) {
array_push($favorisUser,$res->getAnnonces()->getId());
}
}
if (isset($_GET['categories'])) {
$categoriesSearch = $_GET['categories'];
} else {
$categoriesSearch = array();
}
if (isset($_GET['ville'])) {
$ville = $_GET['ville'];
} else {
$ville = '';
}
$villes = $villesRepository->findOneById($ville);
if (isset($_GET['rayon'])) {
$distance = $_GET['rayon'];
} else {
$distance = 50;
}
if (!empty($villes)) {
$lat = $villes->getVilleLatitudeDeg();
$lng = $villes->getVilleLongitudeDeg();
$formule = '(6371 * ACOS(COS(RADIANS(:lat)) * COS(RADIANS(c.VilleLatitudeDeg)) * COS(RADIANS(c.VilleLongitudeDeg) - RADIANS(:lng)) + SIN(RADIANS(:lat)) * SIN(RADIANS(c.VilleLatitudeDeg))))';
$query = $em->createQuery("
SELECT c.id,c.VilleNom, $formule as dist
FROM App\Entity\Villes c
WHERE $formule <= :distance order by dist asc ")->setParameters([
'lat' => $lat,
'lng' => $lng,
'distance' => $distance,
]);
$cities = $query->getResult();
foreach ($cities as $resVille) {
array_push($citiesRes, $resVille['id']);
}
}
$annoncesReq = $annoncesRepository->findByMultiCriteres($categoriesSearch, $citiesRes, $pro, $triSearch, $motscles);
$annonces = array();
$i = -1;
foreach ($annoncesReq as $res) {
$i++;
$annonces[$i]['id'] = $res->getId();
$annonces[$i]['booste'] = $res->isBooster();
$annonces[$i]['titre'] = $res->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$images = $res->getImages();
$annonces[$i]['images'] = (count($images) > 0) ? $images[0]->getLien() : 'default.jpg'; // Chemin de l'image par défaut
$annonces[$i]['pourcentRemise'] = $res->getPourcentRemise();
$annonces[$i]['prix'] = $res->getPrix();
$pourcent = 1 - $res->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getPrix() * $pourcent;
$fin = strtotime($res->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin);
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne'=>$res->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
}
$pagination = $paginator->paginate(
$annonces,
$request->query->getInt('page', 1),
$nbParPage
);
$categories = $categoriesRepository->findAll();
return $this->render('default/annonces.html.twig', [
'categories' => $categories,
'annonces' => $pagination,
'ville' => $ville,
'distance' => $distance,
'categoriesSearch' => $categoriesSearch,
'triSearch' => $triSearch,
'nbParPage' => $nbParPage,
'pro' => $pro,
'motscles' => $motscles,
'favorisUser' => $favorisUser,
'alertes' => $alertes,
]);
}
/**
* @Route("/detailAnonnce/{id}", name="detailAnonnce")
*/
public function detailAnonnce(CategoriesRepository $categoriesRepository, Request $request, $id, AnnoncesRepository $annoncesRepository, AlertesRepository $alertesRepository, NotesEnseignesRepository $notesEnseignesRepository): Response
{
$session = $request->getSession();
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
if (empty($session->get('type'))) {
$session->set('type', 'part');
}
if ($user) {
$session->set('type', $user->getType());
}
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$annoncesReq = $annoncesRepository->findOneById($id);
$annoncesReq->setNbvues($annoncesReq->getNbVues() + 1);
$annoncesRepository->add($annoncesReq, true);
$annonces['id'] = $annoncesReq->getId();
$annonces['booste'] = $annoncesReq->isBooster();
$annonces['titre'] = $annoncesReq->getTitre();
$annonces['enseigne'] = $annoncesReq->getUser()->getRaisonSociale();
$annonces['logo'] = $annoncesReq->getUser()->getLogo();
$annonces['adresse'] = $annoncesReq->getUser()->getAdresse();
$annonces['cp'] = $annoncesReq->getVilles()->getVilleCodePostal();
$annonces['telephone'] = $annoncesReq->getUser()->getTelephone();
$annonces['ville'] = $annoncesReq->getVilles()->getVilleNom();
$images = $annoncesReq->getImages();
$annonces['images'] = (count($images) > 0) ? $images[0]->getLien() : 'default.jpg'; // Utilisez une image par défaut si aucune image n'est disponible
$annonces['pourcentRemise'] = $annoncesReq->getPourcentRemise();
$annonces['prix'] = $annoncesReq->getPrix();
$annonces['description'] = $annoncesReq->getDescription();
$annonces['quantite'] = $annoncesReq->getQuantite();
$annonces['debut'] = $annoncesReq->getDateDebut()->format('d-m-Y H:i');
$annonces['fin'] = $annoncesReq->getDateFin()->format('d-m-Y H:i');
$pourcent = 1 - $annoncesReq->getPourcentRemise() / 100;
$annonces['newprix'] = $annoncesReq->getPrix() * $pourcent;
$fin = strtotime($annoncesReq->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin);
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces['heures'] = $tmp * 24 + $retour['hour'];
$annonces['minutes'] = $retour['minute'];
$annonces['secondes'] = $retour['second'];
$sum = 0;
$moy = 0;
$y = 0;
foreach ($annoncesReq->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces['moyAnnonce'] = $moyAnnonce;
$sum = 0;
$moy = 0;
$y = 0;
$notesEns = $notesEnseignesRepository->findBy(array('Enseigne' => $annoncesReq->getUser()));
foreach ($notesEns as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces['moyEnseigne'] = $noteEnseigne;
return $this->render('default/detailAnonnce.html.twig', [
'annonce' => $annoncesReq,
'alertes' => $alertes,
'categories' => $categories,
'res' => $annonces
]);
}
/**
* @Route("/inscription", name="inscription")
*/
public function inscription(Request $request, PaysRepository $paysRepository, UserRepository $userRepository, VillesRepository $villesRepository, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$session->set('type', $request->query->get('type'));
$type = $request->query->get('type') == 'pro' ? 'pro' : 'part';
$role = $type == 'pro' ? ["ROLE_PRO"] : ["ROLE_PART"];
$credit = $type == 'pro' ? 100 : 0;
$client = new User();
if ($type == 'part') {
$formClient = $this->createFormBuilder($client)
->add('nom', TextType::class, array('label' => false))
->add('prenom', TextType::class, array('label' => false))
->add('adresse', TextType::class, array('label' => false))
->add('codePostal', TextType::class, array('label' => false))
->add('telephone', TextType::class, array('label' => false))
->add('email', EmailType::class, array('label' => false))
->add('password', PasswordType::class, array('label' => false))
->getForm();
} else {
$formClient = $this->createFormBuilder($client)
->add('nom', TextType::class, array('label' => false))
->add('prenom', TextType::class, array('label' => false))
->add('adresse', TextType::class, array('label' => false))
->add('codePostal', TextType::class, array('label' => false))
->add('telephone', TextType::class, array('label' => false))
->add('email', EmailType::class, array('label' => false))
->add('logo', FileType::class, array('label' => false))
->add('password', PasswordType::class, array('label' => false))
->add('raisonSociale', TextType::class, array('label' => false))
->add('siret', TextType::class, array('label' => false))
->add('tva', TextType::class, array('label' => false))
->getForm();
}
$formClientView = $formClient->createView();
$formClient->handleRequest($request);
if ($formClient->isSubmitted()) {
$ville = $villesRepository->findOneById($request->request->get('ville'));
$pays = $paysRepository->findOneById($request->request->get('pays'));
$clientExist = $userRepository->findOneBy(array('email' => $request->request->get('form')['email']));
if ($type == 'pro') {
$file = $formClient->get('logo')->getData();
if ($file != 'null') {
$path = '/';
$fileName = uniqid() . '-' . $file->getClientOriginalName();
$file->move($this->getParameter('logos_directory') . $path, $fileName);
$client->setLogo($fileName);
}
}
if (!empty($clientExist)) {
return $this->redirectToRoute('inscription', ['erreur' => 'email', 'type' => $type], Response::HTTP_SEE_OTHER);
}
$pass = password_hash($request->request->get('form')['password'], PASSWORD_BCRYPT);
$client->setPassword($pass);
$client->setType($type);
$client->setRoles($role);
$client->setCivilite($request->request->get('genre'));
$client->setPays($pays);
$client->setVilles($ville);
$client->setCredits($credit);
$client->setCreated(new DateTime());
$userRepository->add($client, true);
return $this->redirectToRoute('app_login', [], Response::HTTP_SEE_OTHER);
}
$alertes = $alertesRepository->findBy(['User' => $this->getUser()]);
$categories = $categoriesRepository->findAll();
return $this->render('default/inscription.html.twig', [
'form' => $formClientView,
'pays' => $paysRepository->findAll(),
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/profil", name="profil")
*/
public function profil(
Request $request,
PaysRepository $paysRepository,
UserRepository $userRepository,
VillesRepository $villesRepository,
CategoriesRepository $categoriesRepository,
AlertesRepository $alertesRepository,
EntityManagerInterface $entityManager
): Response {
$client = $this->getUser();
$oldLogo = $client->getLogo();
$type = $client->getType();
if ($type == 'part') {
$formClient = $this->createFormBuilder($client)
->add('nom', TextType::class, array('label' => false))
->add('prenom', TextType::class, array('label' => false))
->add('adresse', TextType::class, array('label' => false))
->add('codePostal', TextType::class, array('label' => false))
->add('telephone', TextType::class, array('label' => false))
->add('email', EmailType::class, array('label' => false))
->getForm();
} else {
$formClient = $this->createFormBuilder($client)
->add('nom', TextType::class, array('label' => false))
->add('prenom', TextType::class, array('label' => false))
->add('adresse', TextType::class, array('label' => false))
->add('codePostal', TextType::class, array('label' => false))
->add('telephone', TextType::class, array('label' => false))
->add('email', EmailType::class, array('label' => false))
->add('logo', FileType::class, array('label' => false, 'data_class' => null, 'required'=>false))
->add('raisonSociale', TextType::class, array('label' => false))
->add('siret', IntegerType::class, array('label' => false, 'required'=>false))
->add('tva', TextType::class, array('label' => false, 'required'=>false))
->getForm();
}
$formClientView = $formClient->createView();
$formClient->handleRequest($request);
if ($formClient->isSubmitted()) {
$ville = $villesRepository->findOneById($request->request->get('ville'));
$pays = $paysRepository->findOneById($request->request->get('pays'));
$clientExist = $userRepository->findOneBy(array('email' => $request->request->get('form')['email']));
if (!empty($clientExist) && $clientExist->getId() != $client->getId()) {
return $this->redirectToRoute('profil', ['erreur' => 'email'], Response::HTTP_SEE_OTHER);
}
if ($type == 'pro') {
// Gérer la suppression du logo
if ($request->request->get('remove_logo') == '1') {
$client->setLogo(null);
} else {
$file = $formClient->get('logo')->getData();
if ($file) {
$fileName = uniqid() . '-' . $file->getClientOriginalName();
$file->move($this->getParameter('logos_directory'), $fileName);
$client->setLogo($fileName);
} else {
$client->setLogo($oldLogo);
}
}
}
$client->setPays($pays);
$client->setVilles($ville);
$userRepository->add($client, true);
return $this->redirectToRoute('profil', [], Response::HTTP_SEE_OTHER);
}
if ($request->request->get('new1')) {
$pass = password_hash($request->request->get('new1'), PASSWORD_BCRYPT);
$client->setPassword($pass);
$userRepository->add($client, true);
}
$alertes = $alertesRepository->findBy(['User' => $client]);
$categories = $categoriesRepository->findAll();
return $this->render('default/profil.html.twig', [
'pays' => $paysRepository->findAll(),
'form' => $formClientView,
'alertes' => $alertes,
'categories' => $categories
]);
}
/**
* @Route("/favoris", name="favoris")
*/
public function favoris(Request $request, AnnoncesRepository $annoncesRepository, FavorisRepository $favorisRepository, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$session = $request->getSession();
$session->set('type', 'part');
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
$annoncesRes = $favorisRepository->findBy(['User' => $user]);
$annonces = array();
$i = -1;
foreach ($annoncesRes as $res) {
$i++;
$annonces[$i]['id'] = $res->getAnnonces()->getId();
$annonces[$i]['booste'] = $res->getAnnonces()->isBooster();
$annonces[$i]['titre'] = $res->getAnnonces()->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$annonces[$i]['images'] = $res->getAnnonces()->getImages()[0]->getLien();
$annonces[$i]['pourcentRemise'] = $res->getAnnonces()->getPourcentRemise();
$annonces[$i]['prix'] = $res->getAnnonces()->getPrix();
$pourcent = 1 - $res->getAnnonces()->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getAnnonces()->getPrix() * $pourcent;
$fin = strtotime($res->getAnnonces()->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin);
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getAnnonces()->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getUser()->getNotesEnseignes() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
}
return $this->render('default/favoris.html.twig', [
'annonce' => $annonces,
'alertes' => $alertes,
'categories' => $categories
]);
}
/**
* @Route("/addFavoris", name="addFavoris")
*/
public function addFavoris(Request $request, AnnoncesRepository $annoncesRepository, FavorisRepository $favorisRepository): Response
{
$user = $this->getUser();
$id = $request->request->get('id');
$etat = $request->request->get('etat');
$annonce = $annoncesRepository->findOneById($id);
if($etat == 'non active') {
$favoris = new Favoris();
$favoris->setUser($user);
$favoris->setDate(new Datetime);
$favoris->setAnnonces($annonce);
$favorisRepository->add($favoris, true);
} else {
$favoris = $favorisRepository->findOneBy(array('User'=>$user,'Annonces'=>$annonce));
$favorisRepository->remove($favoris, true);
}
return new Response('ok');
}
/**
* @Route("/contact", name="contact")
*/
public function contact(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$lienAnnonce = $request->query->get('id') ? $request->headers->get('referer') : '';
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/contact.html.twig', [
'lienAnnonce' => $lienAnnonce,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/contact1", name="contact1")
*/
public function contact1(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/contact1.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/achatFacture", name="achatFacture")
*/
public function achatFacture(Request $request, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
return $this->render('default/achatGenerationFacture.html.twig', [
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/notesEnseignes", name="notesEnseignes")
*/
public function notesEnseignes(Request $request, NotesEnseignesRepository $notesEnseignesRepository, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$notes = $notesEnseignesRepository->findBy(['Enseigne' => $this->getUser()], ['Date' => 'desc']);
$sum = 0;
$moy = 0;
$y = 0;
$noteEnseigne = 0;
foreach ($notes as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$noteEnseigne = $sum / $y;
}
$alertes = $alertesRepository->findBy(['User' => $this->getUser()]);
$categories = $categoriesRepository->findAll();
return $this->render('default/notesEnseignes.html.twig', [
'notes' => $notes,
'noteEnseigne' => $noteEnseigne,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/notesAnnonces/{id}", name="notesAnnonces")
*/
public function notesAnnonces(Request $request, NotesAnnoncesRepository $notesAnnoncesRepository, $id, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$notes = $notesAnnoncesRepository->findBy(['Annonces' => $id], ['Date' => 'desc']);
$sum = 0;
$moy = 0;
$y = 0;
$noteAnnonces = 0;
foreach ($notes as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$noteAnnonces = $sum / $y;
}
$alertes = $alertesRepository->findBy(['User' => $this->getUser()]);
$categories = $categoriesRepository->findAll();
return $this->render('default/notesAnnonces.html.twig', [
'notes' => $notes,
'noteAnnonces' => $noteAnnonces,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/mesAnnonces/{type}", name="mesAnnonces")
*/
public function mesAnnonces(Request $request, AnnoncesRepository $annoncesRepository, FavorisRepository $favorisRepository, $type, AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$user = $this->getUser();
$alertes = $alertesRepository->findBy(['User' => $user]);
$categories = $categoriesRepository->findAll();
$annoncesRes = $type == 'encours'
? $annoncesRepository->findByAnnoncesEnCours($user->getId())
: $annoncesRepository->findByAnnoncesExpire($user->getId());
$annonces = array();
$i = -1;
foreach ($annoncesRes as $res) {
$i++;
$annonces[$i]['id'] = $res->getId();
$annonces[$i]['booste'] = $res->isBooster();
$annonces[$i]['titre'] = $res->getTitre();
$annonces[$i]['enseigne'] = $res->getUser()->getRaisonSociale();
$image = $res->getImages()[0] ?? null;
$annonces[$i]['images'] = $image ? $image->getLien() : null;
$annonces[$i]['pourcentRemise'] = $res->getPourcentRemise();
$annonces[$i]['prix'] = $res->getPrix();
$annonces[$i]['nbVues'] = $res->getNbVues();
$pourcent = 1 - $res->getPourcentRemise() / 100;
$annonces[$i]['newprix'] = $res->getPrix() * $pourcent;
$fin = strtotime($res->getDateFin()->format('Y-m-d H:i:s'));
$debut = strtotime(date('Y-m-d H:i:s'));
$diff = abs($debut - $fin);
$retour = array();
$tmp = $diff;
$retour['second'] = $tmp % 60;
$tmp = floor(($tmp - $retour['second']) / 60);
$retour['minute'] = $tmp % 60;
$tmp = floor(($tmp - $retour['minute']) / 60);
$retour['hour'] = $tmp % 24;
$tmp = floor(($tmp - $retour['hour']) / 24);
$retour['day'] = $tmp * 24;
$annonces[$i]['heures'] = $tmp * 24 + $retour['hour'];
$annonces[$i]['minutes'] = $retour['minute'];
$annonces[$i]['secondes'] = $retour['second'];
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getNotesAnnonces() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
if ($y > 0) {
$moy = $sum / $y;
$moyAnnonce = (round($moy * 2) / 2);
} else {
$moyAnnonce = 0;
}
$annonces[$i]['moyAnnonce'] = $moyAnnonce;
$sum = 0;
$moy = 0;
$y = 0;
foreach ($res->getUser()->getNotesEnseignes() as $res2) {
$y++;
$sum = $sum + $res2->getNote();
}
$maxNote = $y * 5;
if ($maxNote > 0) {
$noteEnseigne = ($sum * 100) / $maxNote;
} else {
$noteEnseigne = 0;
}
$annonces[$i]['moyEnseigne'] = $noteEnseigne;
}
return $this->render('default/mesAnnonces.html.twig', [
'annonces' => $annonces,
'type' => $type,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/addAlertes", name="addAlertes", methods={"POST"})
*/
public function addAlertes(Request $request, EntityManagerInterface $entityManager, VillesRepository $villesRepository, CategoriesRepository $categoriesRepository): Response
{
$alerte = new Alertes();
$alerte->setUser($this->getUser());
$texte = $request->request->get('texte');
if ($texte) {
$alerte->setTexte($texte);
}
$categorieId = $request->request->get('categorie');
if ($categorieId) {
$categorie = $categoriesRepository->find($categorieId);
$alerte->setCategories($categorie);
}
$villeId = $request->request->get('ville');
if ($villeId) {
$ville = $villesRepository->find($villeId);
$alerte->setVilles($ville);
}
$rayon = $request->request->get('rayon');
if ($rayon) {
$alerte->setRayon($rayon);
}
$entityManager->persist($alerte);
$entityManager->flush();
return $this->redirectToRoute('profil');
}
/**
* @Route("/delete-alert/{id}", name="delete_alert", methods={"DELETE"})
*/
public function deleteAlert($id, AlertesRepository $alertesRepository, EntityManagerInterface $entityManager): JsonResponse
{
$alerte = $alertesRepository->find($id);
if (!$alerte || $alerte->getUser() !== $this->getUser()) {
return new JsonResponse(['error' => 'Alerte non trouvée ou accès non autorisé'], Response::HTTP_NOT_FOUND);
}
$entityManager->remove($alerte);
$entityManager->flush();
return new JsonResponse(['success' => 'Alerte supprimée'], Response::HTTP_OK);
}
/**
* @Route("/paiement", name="paiement")
*/
public function paiement(AlertesRepository $alertesRepository, CategoriesRepository $categoriesRepository): Response
{
$date = date('d/m/Y:h:i:s');
$contextCmd = 'ewogICAiYmlsbGluZyI6ewogICAgICAiZmlyc3ROYW1lIjoiSsOpcsOpbXkiLAogICAgICAibGFzdE5hbWUiOiJHcmltbSIsCiAgICAgICJhZGRyZXNzTGluZTEiOiIzIHJ1ZSBkZSBsJ8OpZ2l
zZSIsCiAgICAgICJjaXR5IjoiT3N0aGVpbSIsCiAgICAgICJwb3N0YWxDb2RlIjoiNjgxNTAiLAogICAgICAiY291bnRyeSI6IkZSIiwKICAgfSwKICAgInNoaXBwaW5nIjp7CiAgICAgICJmaXJzdE5hbWUiOiJKw6lyw6lteSIsCiAgICAgICJsYXN0TmFtZSI6IkdyaW1tIiwKICAgICAgImFkZHJlc3NMaW5lMSI6IjMgcnVlIGRlIGwnw6lnbGlzZSIsCiAgICAgICJjaXR5IjoiT3N0aGVpbSIsCiAgICAgICJwb3N0YWxDb2RlIjoiNjgxNTAiLAogICAgICAiY291bnRyeSI6IkZSIiwKICAgICAgImVtYWlsIjoiamVyZW02OEBob3RtYWlsLmNvbSIsCiAgICAgICJwaG9uZSI6IiszMy02MTIzNDU2NzgiLAogICAgICAic2hpcEluZGljYXRvciI6ImJpbGxpbmdfYWRkcmVzcyIsCiAgICAgICJkZWxpdmVyeVRpbWVmcmFtZSI6InR3b19kYXkiLAogICAgICAiZmlyc3RVc2VEYXRlIjoiMjAxNy0wMS0yNSIsCiAgICAgICJtYXRjaEJpbGxpbmdBZGRyZXNzIjp0cnVlCiAgIH0sCiAgICJjbGllbnQiOnsKICAgICAgImVtYWlsIjoiamVyZW02OEBob3RtYWlsLmNvbSIsCiAgICAgICJtb2JpbGVQaG9uZSI6IiszMy02MTIzNDU2NzgiLAogICAgICAiYmlydGhDaXR5IjoiQ29sbWFyIiwKICAgICAgImJpcnRoUG9zdGFsQ29kZSI6IjY4MDAwIiwKICAgICAgImJpcnRoQ291bnRyeSI6IkZSIiwKICAgICAgImJpcnRoZGF0ZSI6IjE5ODctMDMtMjciCiAgIH0KfQ==';
$cle_secrete = '9CC0C314AA4843441B1E1FB90A1BD992D4AD4A94';
$mac = "TPE=7199003*contexte_commande=".$contextCmd."*date=".$date."*lgue=FR*mail=contact@modixom.fr*montant=62.73EUR*reference=MODIXOM1234*societe=modixom*texte-libre=ExempleTexteLibre*version=3.0";
$sceau_mac = hash_hmac('sha1', $mac, $cle_secrete,false);
$alertes = $alertesRepository->findBy(['User' => $this->getUser()]);
$categories = $categoriesRepository->findAll();
return $this->render('default/paiement.html.twig', [
"mac" => $sceau_mac,
'date' => $date,
'contextCmd' => $contextCmd,
'alertes' => $alertes,
'categories' => $categories,
]);
}
/**
* @Route("/retourpaiement", name="retourpaiement")
*/
public function retourpaiement(): Response
{
dd('ok');
}
/**
* @Route("/test-geonames-api", name="test_geonames_api")
*/
public function testGeoNamesApi(): Response
{
return $this->render('tests/GeoNamesApiTest.html.twig');
}
}