<?php

namespace App\Controller;

use App\Entity\Notification;
use App\Repository\NotificationRepository;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

#[Route('/notification', name: 'notification_')]
class NotificationController extends AbstractController
{
    #[Route('/', name: 'list')]
    public function list(
        PaginatorInterface $paginator,
        Request $request,
        NotificationRepository $NotificationRepository
    ): Response {
        return $this->render('notification/list.html.twig', [
            'controller_name' => 'NotificationController',
            'pagination' => $paginator->paginate(
                $NotificationRepository->listForUser($this->getUser())
                                                ->order(['readed' => 'ASC', 'createdAt' => 'DESC'])
                                                ->getResult(),
                $request->query->getInt('page', 1)
            )
        ]);
    }

    #[Route('/delete/{id}', name: 'delete')]
    #[IsGranted('delete', subject: 'Notification', message: 'granted_not_allowed_delete_notification')]
    public function delete(Notification $Notification, Request $Request): Response
    {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($Notification);
        try {
            $entityManager->flush();
        } catch (\Throwable $th) {
            if ($_ENV['APP_ENV'] === 'dev') {
                throw $th; //DEBUG
            }
            $this->addFlash('warning', 'alert_error_deleting_notification');
        }

        if (null != $Request->headers->get('referer')) {
            return $this->redirect($Request->headers->get('referer'));
        }
        return $this->redirectToRoute('notification_list');
    }

    #[Route('/markread/{id}', name: 'markread')]
    #[IsGranted('markread', subject: 'Notification', message: 'granted_not_allowed_markread_notification')]
    public function markread(Notification $Notification, Request $Request): Response
    {
        $entityManager = $this->getDoctrine()->getManager();
        $Notification->setReaded(true);
        try {
            $entityManager->flush();
        } catch (\Throwable $th) {
            if ($_ENV['APP_ENV'] === 'dev') {
                throw $th; //DEBUG
            }
            $this->addFlash('warning', 'alert_error_markread_notification');
        }

        if (null != $Request->headers->get('referer')) {
            return $this->redirect($Request->headers->get('referer'));
        }
        return $this->redirectToRoute('notification_list');
    }
}
