<?php
namespace App\Controller\Front;
use DateTime;
use Exception;
use DateInterval;
use App\Entity\Post;
use App\Entity\User;
use App\Form\PostType;
use App\Form\RegisterType;
use App\Entity\DebanRequest;
use App\Form\DebanRequestType;
use App\EmailNotification\ToUser;
use App\Repository\PostRepository;
use App\Repository\UserRepository;
use Symfony\Component\Form\FormError;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Mercure\Discovery;
use App\Repository\NotificationRepository;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Mercure\Authorization;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class HomepageController extends AbstractController
{
#[Route('/coming-soon', name: 'coming_soon')]
public function comingSoon(Request $request): Response
{
$session = $request->getSession();
if ($request->request->get('accessPassword')) {
$truePassword = "P2lhNLVt1y";
if ($request->request->get('accessPassword') == $truePassword) {
$expire = new DateTime();
$expire->add(new DateInterval("P5D"));
$cookie = Cookie::create('politicly-production-access')
->withValue(true)
->withExpires($expire)
->withSecure(true);
$response = $this->redirectToRoute('feed');
$session->remove('wrong-password');
$response->headers->setCookie($cookie);
return $response;
}
else {
$session->set('wrong-password', true);
return $this->redirectToRoute('coming_soon');
}
}
return $this->render('front/coming-soon.html.twig', [
'coming' => true
]);
}
#[Route('/bienvenue', name: 'user_welcome')]
public function welcome(Request $request, UserRepository $userRepository, Session $session): Response
{
$form = $this->createForm(RegisterType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$data = $form->getData();
/* Check if user already exist */
$existUser = $userRepository->findOneBy(['email' => $data['email']]);
if ($existUser)
{
$form->get('email')->addError(new FormError("Un compte existe avec cet email"));
}
else
{
try {
$date = date_create_from_format('d/m/Y', $data['birthDate']);
} catch (Exception) {
$form->get('birthDate')->addError(new FormError("Veuillez renseigner une date valide"));
return $this->render('front/welcome.html.twig', [
'menu' => 'welcome',
'form' => $form->createView()
]);
}
if ($date > new DateTime("-13 years")) {
$form->get('birthDate')->addError(new FormError("Vous devez avoir plus de 13 ans pour vous inscrire"));
return $this->render('front/welcome.html.twig', [
'menu' => 'welcome',
'form' => $form->createView()
]);
}
if ($date < new DateTime("-130 years")) {
$form->get('birthDate')->addError(new FormError("Veuillez renseigner une date valide"));
return $this->render('front/welcome.html.twig', [
'menu' => 'welcome',
'form' => $form->createView()
]);
}
/* Set info user */
$session->set('email', $data['email']);
$session->set('password', $data['password']);
$session->set('firstname', $data['firstname']);
$session->set('lastname', $data['lastname']);
$session->set('genre', $data['genre']);
$session->set('phone', $data['phone']);
$session->set('birthDate', $data['birthDate']);
return $this->render('front/registration/info-type-registration.html.twig');
}
}
return $this->render('front/welcome.html.twig', [
'menu' => 'welcome',
'form' => $form->createView()
]);
}
#[Route('/', name: 'feed')]
public function feed(PostRepository $postRepo, Request $request): Response
{
/** @var User $user */
$user = $this->getUser();
$post = new Post();
$post->setHandleRedirect('feed');
$form = $this->createForm(PostType::class, $post, [
'action' => $this->generateUrl('handle_post_submit')
]);
$form->handleRequest($request);
$posts = $postRepo->feedByUser($user);
if (count($posts) < 10) {
foreach ($postRepo->feedByUserRandom($user) as $post) { $posts[] = $post; }
}
return $this->render('front/feed.html.twig', [
'menu' => 'feed',
'user' => $user,
'showing' => 'owner',
'type' => $user->getType(),
'posts' => $posts,
'form' => $form->createView(),
'totalPost' => $postRepo->getTotalPostVisible()
]);
}
#[Route('/discover-notifications', name: 'discover_notifications')]
public function discover(Request $request, Discovery $discovery, Authorization $authorization): JsonResponse
{
// Link: <https://hub.example.com/.well-known/mercure>; rel="mercure"
$discovery->addLink($request);
$authorization->setCookie($request, ['*']);
return $this->json([true]);
}
#[Route('/mes-notifications', name: 'responsive_notifications')]
public function responsiveNotifications(EntityManagerInterface $manager, NotificationRepository $notificationRepo)
{
/** @var User $user */
$user = $this->getUser();
$user->setNotificationsOpen(true)
->setLastNotificationsOpening(new DateTime());
$manager->persist($user);
$manager->flush();
$lastNotifications = $notificationRepo->findBy(['owner' => $user], ['id' => 'DESC'], 30);
$notifications = [];
$date = new DateTime();
foreach ($lastNotifications as $notification) {
$notificationDate = $notification->getCreatedAt();
$diff = $notificationDate->diff($date);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;
if ($seconds < 60 ) {
$notificationInterval = '1 min';
}
else if ($seconds >= 60 && $seconds < 3600 ) {
$notificationInterval = intval($seconds / 60) . ' min';
}
else if ($seconds >= 3600 && $seconds < 86400) {
$notificationInterval = intval($seconds / 3600) . ' h';
}
else if ($seconds >= 86400 && $seconds < 604800) {
$notificationInterval = intval($seconds / 86400) . ' j';
}
else if ($seconds >= 604800 && $seconds < 2 * 604800) {
$notificationInterval = intval($seconds / 604800) . ' semaine';
}
else {
$notificationInterval = intval($seconds / 604800) . ' semaines';
}
$formattedNotification = [
'id' => $notification->getId(),
'avatar' => $notification->getRelatedUser()->getAvatar(),
'fullname' => $notification->getRelatedUser()->getFullname(),
'content' => $notification->getContent(),
'date' => $notificationInterval,
'status' => !$notification->getIsOpened() ? 'new' : ''
];
$notifications[] = $formattedNotification;
}
return $this->render('front/shared/responsive-notifications.html.twig', [
'menu' => 'notification',
'user' => $user,
'showing' => 'owner',
'type' => $user->getType(),
'notifications' => $notifications
]);
}
#[Route('/retrieve-post-video', name: 'retrieve_post_video')]
public function retrievePostVideo(Request $request, PostRepository $postRepo): Response
{
$data = json_decode($request->getContent(), true);
$postId = $data["postId"];
$post = $postRepo->find($postId);
$videoPath = $this->generateUrl('feed') . 'images/medias/' . $post->getVideo();
return new JsonResponse(['videoPath' => $videoPath]);
}
#[Route('/email', name: 'email')]
public function email(ToUser $toUser): Response
{
$toUser->testEmail();
return $this->render('email/test-email.html.twig');
}
#[Route('/report-contact/{token}', name: 'report_contact')]
public function reportContact(User $user, Request $request, EntityManagerInterface $manager): Response
{
$debanRequest = new DebanRequest();
$form = $this->createForm(DebanRequestType::class, $debanRequest);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$debanRequest->setUser($user);
$manager->persist($debanRequest);
$manager->flush();
$this->addFlash("success", "Votre demande a bien été pris en compte");
return $this->redirectToRoute('user_welcome');
}
return $this->render('/front/citizen/deban-request.html.twig', [
'form' => $form->createView()
]);
}
}