<?php
namespace App\Controller;
use App\Entity\Livre;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Favori;
use App\Entity\Demande;
use App\Entity\Notification;
use App\Form\LivreType;
use App\Data\SearchData;
use App\Form\SearchForm;
use App\Repository\NotificationRepository;
use App\Repository\LivreRepository;
use App\Repository\DemandeRepository;
use App\Repository\FavoriRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @Route("/")
*/
class LivreController extends AbstractController
{
/**
* @Route("/loginadmin", name="loginadmin")
*/
public function loginadmin(AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('admin/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
/**
* @Route("/", name="app_livre_index", methods={"GET"})
*/
public function index(Request $request, LivreRepository $livreRepository, PaginatorInterface $paginator): Response
{
$data = new SearchData();
$form = $this->createForm(SearchForm::class, $data);
// $cats = $catRepo->findAll();
$form->handleRequest($request);
$isset = $form->isSubmitted();
$livresPage = $livreRepository->findSearch($data);
$livres = $paginator->paginate(
$livresPage,
$request->query->getInt('page', 1),
10
);
$lastbooks = $livreRepository->findBy([], ['id' => 'DESC'], 10);
// dd($lastbooks);
return $this->render('livre/index.html.twig', [
'livres' => $livres,
'isset' => $isset,
'form' => $form->createView(),
'lastbooks' => $lastbooks,
]);
// $livres = $paginator->paginate(
// $livreRepository->nosLivres(),
// $request->query->getInt('page', 1),
// 10
// );
// return $this->render('livre/index.html.twig', [
// 'livres' => $livres,
// ]);
}
/**
* @Route("/new", name="app_livre_new", methods={"GET", "POST"})
* @Route("/edit/{id}", name="edit")
*/
public function new(Livre $livre = null,Request $request, LivreRepository $livreRepository): Response
{
if(!$livre){
$livre = new Livre();
}
$form = $this->createForm(LivreType::class, $livre);
$form->handleRequest($request);
$user = $this->get('security.token_storage')->getToken()->getUser();
if ($form->isSubmitted() && $form->isValid()) {
$image = $form->get('image')->getData();
if($image){
$allowTypes = ['jpg', 'png', 'jpeg', 'gif','webp'];
if (in_array($image->guessExtension(), $allowTypes)) {
$fichier = md5(uniqid()) . '.png';
//$helpers->compressImage($image->getPathName(), $this->getParameter('images_directory') . '/' . $fichier, 75);
$destination = $this->getParameter('images_directory');
$image->move(
$destination,
$fichier
);
$livre->setPhoto($fichier);
} else {
$this->addFlash('erreur', $fichier . " n'est pas une image ");
return new RedirectResponse($request->headers->get('referer'));
}
}
$livre->setUser($user);
$livre->setStatus(1);
$livreRepository->add($livre, true);
return $this->redirectToRoute('app_livre_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('livre/new.html.twig', [
'livre' => $livre,
'editMode' => $livre->getId() !== null,
'form' => $form,
]);
}
/**
* @Route("/login", name="login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils)
{
if ($this->isGranted('ROLE_USER')) {
return $this->redirectToRoute('app_livre_index');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$session = $request->getSession();
return $this->render('livre/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
/**
* @Route("/message/{message}", name="message", methods={"GET", "POST"})
*/
public function message(String $message)
{
return $this->render('livre/message.html.twig', [
'message' => $message,
]);
}
/**
* @Route("/mesLivres", name="mesLivres")
*/
public function mesLivres(LivreRepository $repo)
{
if ($this->isGranted('ROLE_USER')) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$livres = $repo->findBy(['user' => $user->getId()]);
// dd($livres);
return $this->render('user/mesLivres.html.twig', [
'livres' => $livres,
]);
} else {
return $this->redirectToRoute('login');
}
}
/**
* @Route("/mesFavoris", name="mesFavoris")
*/
public function memFavoris(FavoriRepository $repo)
{
if ($this->isGranted('ROLE_USER')) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$favoris = $repo->findBy(['User' => $user->getId()]);
// dd($livres);
return $this->render('user/mesFavoris.html.twig', [
'favoris' => $favoris,
]);
} else {
return $this->redirectToRoute('login');
}
}
/**
* @Route("/addfavori/{id}", name="addfavori", methods={"GET", "POST"})
*/
public function addfavori(Request $request, livre $livre ,FavoriRepository $favoriRepository,EntityManagerInterface $manager): Response
{
if ($this->isGranted('ROLE_USER')) {
$favori = new Favori();
$user = $this->get('security.token_storage')->getToken()->getUser();
$existingFavori = $favoriRepository->findOneBy([
'User' => $user,
'livre' => $livre,
]);
if ($existingFavori) {
$this->addFlash('error', 'Ce livre est déjà ajouté aux favoris.');
} else {
$favori->setUser($user);
$favori->setLivre($livre);
$manager->persist($favori);
$manager->flush();
$this->addFlash('success', 'Le livre a été ajouté aux favoris.');
}
return $this->redirectToRoute('app_livre_index');
} else {
return $this->redirectToRoute('login');
}
// return $this->redirectToRoute('message', ['message' => $message]);
}
/**
* @Route("/livre/{id}/removeFavori", name="removeFavori",methods={"DELETE","POST"})
*/
public function removeFavori(Request $request, Favori $favori, EntityManagerInterface $manager)
{
if ($this->isCsrfTokenValid('remove' . $favori->getId(), $request->request->get('csrf_token'))) {
$manager->remove($favori);
$manager->flush();
}
return $this->redirectToRoute('mesFavoris');
}
/**
* @Route("/livre/{id}/remove", name="remove",methods={"DELETE","POST"})
*/
public function remove(Request $request, Livre $livre, EntityManagerInterface $em)
{
if ($this->isCsrfTokenValid('remove' . $livre->getId(), $request->request->get('csrf_token'))) {
$livre->setStatus(3);
$em->persist($livre);
$em->flush();
}
return $this->redirectToRoute('mesLivres');
}
/**
* @Route("/logout", name="logout")
*/
public function logout()
{
}
/**
* @Route("/{id}", name="app_livre_show", methods={"GET"})
*/
public function show(Livre $livre, DemandeRepository $demandeRepo, TranslatorInterface $trans): Response
{
if ($this->isGranted('ROLE_USER')) {
$user = $this->get('security.token_storage')->getToken()->getUser();
//vérifier si l'user a déjà demandé ce livre
$demande = $demandeRepo->findBy(['user' => $user,'livre' => $livre]);
if($demande){
return $this->redirectToRoute('message', ['message' => $trans->trans("you already requested this book")]);
}
}
return $this->render('livre/show.html.twig', [
'livre' => $livre,
]);
}
/**
* @Route("/{id}/edit", name="app_livre_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, Livre $livre, LivreRepository $livreRepository): Response
{
$form = $this->createForm(LivreType::class, $livre);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$livreRepository->add($livre, true);
return $this->redirectToRoute('app_livre_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('livre/edit.html.twig', [
'livre' => $livre,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_livre_delete", methods={"POST"})
*/
public function delete(Request $request, Livre $livre, LivreRepository $livreRepository): Response
{
if ($this->isCsrfTokenValid('delete'.$livre->getId(), $request->request->get('_token'))) {
$livreRepository->remove($livre, true);
}
return $this->redirectToRoute('app_livre_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/choix_livre/{id}/{demande}", name="choix_livre", methods={"GET", "POST"})
*/
public function choixLivre(Request $request, livre $livre, Demande $demande ,DemandeRepository $demandeRepository, NotificationRepository $notifRepo,EntityManagerInterface $manager, TranslatorInterface $trans): Response
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$demande->setStatus(2);
$demande->setLivre2($livre);
$demande->setDate(new \DateTime());
$manager->persist($demande);
$manager->flush();
$livre->setStatus(2);
$manager->persist($livre);
$manager->flush();
$notif1 = new Notification();
$notif1->setUser($livre->getUser());
$notif1->setStatus(1);
$notif1->setDemande($demande);
$notifRepo->add($notif1, true);
$existingNotif = $notifRepo->findOneBy([
'user' => $user,
'demande' => $demande,
]);
$existingNotif->setStatus(1);
// $notif2 = new Notification();
// $notif2->setUser($user);
// $notif2->setStatus(1);
// $notif2->setDemande($demande);
// $notifRepo->add($notif2, true);
$message = $trans->trans("your choice is confirmed, please contact the owner on ". $livre->getUser()->getEmail());
return $this->redirectToRoute('message', ['message' => $message]);
}
/**
* @Route("/markas/seen", name="markassuun", methods={"POST","GET"})
*/
public function markassuun(Request $request, NotificationRepository $notificationRepository, EntityManagerInterface $manager)
{
// Perform your quick action here
// Example: Update database, send email, etc.
$notifications = $notificationRepository->findBy(['user' => $this->get('security.token_storage')->getToken()->getUser()]);
// Marquer toutes les notifications comme "seen"
foreach ($notifications as $notification) {
$notification->setStatus(2);
}
// Enregistrer les modifications dans la base de données
$manager->flush();
// Return a JSON response indicating success
return new JsonResponse(['success' => true]);
}
/**
* @Route("/create_demande/{id}", name="create_demande", methods={"GET", "POST"})
*/
public function createDemande(Request $request,LivreRepository $livreRepo, livre $livre ,NotificationRepository $notificationRepo, DemandeRepository $demandeRepository, EntityManagerInterface $manager, TranslatorInterface $trans): Response
{
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user==$livre->getUser()){
$message = $trans->trans("Impossible to exchange with your own book");
return $this->redirectToRoute('message', ['message' => $message]);
}
$demande = new Demande();
$demande->setUser($user);
$demande->setLivre($livre);
$demande->setStatus(1);
$demande->setDate(new \DateTime());
$livre->setStatus(2);
$manager->persist($livre);
$manager->flush();
$demandeRepository->add($demande, true);
$notification = new Notification();
$notification->setUser($livre->getUser());
$notification->setStatus(1);
$notification->setDemande($demande);
$notificationRepo->add($notification, true);
$message = $trans->trans("Your reservation has been successfully registered and requires validation within 48 hours from now");
return $this->redirectToRoute('message', ['message' => $message]);
// return $this->render('livre/message.html.twig', [
// 'message' => $message,
// ]);
}
/**
* @Route("/demande/notificationt", name="notif", methods={"GET"})
*/
public function notif(DemandeRepository $demandeRepo)
{
if ($this->isGranted('ROLE_USER')) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$demandes = $demandeRepo->demandes($user->getId());
$demande2 = $demandeRepo->findBy(['user' => $user,'status' => 2]);
$mergedArray = array_merge($demandes, $demande2);
uasort($mergedArray, function($a, $b) {
return $b->getDate() <=> $a->getDate();
});
// Sort the array
// usort($mergedArray, 'datecompare');
dump($mergedArray);
return $this->render('livre/notif.html.twig', [
'count' => count($mergedArray),
"demandes" => $mergedArray,
"user" => $user
]);
} else {
return new Response(null, Response::HTTP_OK);
}
}
/**
* @Route("/demande/notificationt2", name="notif2", methods={"GET"})
*/
public function notif2(NotificationRepository $notificationRepo)
{
if ($this->isGranted('ROLE_USER')) {
$user = $this->get('security.token_storage')->getToken()->getUser();
$notifications = $notificationRepo->findBy(['user' => $user->getId()],['id' => 'DESC'],5);
// $demande2 = $notificationRepo->findBy(['user' => $user,'status' => 2]);
// count des notif non lu parmis 5 dernier ;
// $count="4";
$count = $notificationRepo->count([
'user' => $user,
'status' => 1
]);
return $this->render('livre/notif2.html.twig', [
'count' => $count,
"notifications" => $notifications,
"user" => $user
]);
} else {
return new Response(null, Response::HTTP_OK);
}
}
/**
* @Route("/change-locale/{locale}", name="change_locale")
*/
public function changeLocale($url =null,$locale, Request $request)
{
$request->getSession()->set('_locale', $locale);
if($url){
$urlbase = $request->server->get("HTTP_HOST");
return $this->redirect('http://'.$urlbase.'/'.$url);
}
if ($request->headers->get('referer')) {
return $this->redirect($request->headers->get('referer'));
}
return $this->redirectToRoute('app_livre_index');
}
/**
* @Route("/cancel/{livre}/{demande}", name="app_echange_cancel", methods={"GET"})
*/
public function cancelEchange(Livre $livre, Demande $demande,EntityManagerInterface $manager): Response
{
$demande->setStatus(3);
$demande->setDate(new \DateTime());
$manager->persist($demande);
$manager->flush();
$livre->setStatus(3);
$manager->persist($livre);
$manager->flush();
// to referer
return $this->redirectToRoute('app_livre_index');
}
}