<?php
namespace App\Controller;
use App\Component\Tabs\Tab;
use App\Component\Tabs\Tabs;
use App\Entity\Notification;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class NotificationController extends ABaseController
{
#[Route('/notifications', name: 'route.notifications')]
public function index(Request $request): Response
{
$notificationsNotReadCount = $this->getNotificationsNotReadCount();
$tabs = new Tabs('tabs');
$tabs->addTab('all', new Tab('Všechny', $this->generateUrl('route.notifications')));
$tabs->addTab('not_read', new Tab('Nepřečtené (<span class="notification-count">' . $notificationsNotReadCount . '</span>)',
$this->generateUrl('route.notifications', ['not_read' => true])));
if ($request->get('not_read')) {
$tabs->setActive('not_read');
$notifications = $this->getEntityManager()->getRepository(Notification::class)->getNotReadByUser($this->getUser())
->getQuery()->getResult();
} else {
$tabs->setActive('all');
$notifications = $this->getEntityManager()->getRepository(Notification::class)->getByUser($this->getUser())
->getQuery()->getResult();
}
return $this->render('notification/index.html.twig', [
'notifications' => $notifications,
'tabs' => $tabs
]);
}
#[Route('/notifications/ajax/read', name: 'route.notifications.ajax.read')]
public function markAsReadAction(Request $request): Response
{
return $this->markAs($request);
}
#[Route('/notifications/ajax/not_read', name: 'route.notifications.ajax.not_read')]
public function markAsNotReadAction(Request $request): Response
{
return $this->markAs($request, false);
}
public function findNotification(int $id): Notification
{
$notification = $this->getEntityManager()->getRepository(Notification::class)->find($id);
if (!$notification instanceof Notification) {
throw new \Exception('Notification not found');
}
return $notification;
}
protected function markAs(Request $request, bool $read = true): Response
{
$id = $request->get('id');
try {
$notification = $this->findNotification($id);
} catch (\Throwable $exception) {
return new Response($exception->getMessage());
}
if ($read) {
$notification->markAsRead();
} else {
$notification->markAsNotRead();
}
$this->getEntityManager()->flush();
return new JsonResponse([
'count' => $this->getNotificationsNotReadCount()
]);
}
protected function getNotificationsNotReadCount(): int
{
$notificationsNotReadCount = $this->getEntityManager()->getRepository(Notification::class)->getNotReadByUserCount($this->getUser());
return $notificationsNotReadCount;
}
}