<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CalendarBundle\Controller;

use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Repository\InviteRepository;
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepositoryInterface;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Routing\Annotation\Route;

class MyInvitationsController extends AbstractController
{
    public function __construct(private readonly InviteRepository $inviteRepository, private readonly PaginatorFactory $paginator, private readonly DocGeneratorTemplateRepositoryInterface $docGeneratorTemplateRepository) {}

    #[Route(path: '/{_locale}/calendar/invitations/my', name: 'chill_calendar_invitations_list_my')]
    public function myInvitations(Request $request): Response
    {
        $this->denyAccessUnlessGranted('ROLE_USER');

        $user = $this->getUser();

        if (!$user instanceof User) {
            throw new UnauthorizedHttpException('you are not a user');
        }

        $total = count($this->inviteRepository->findBy(['user' => $user]));
        $paginator = $this->paginator->create($total);

        $invitations = $this->inviteRepository->findBy(
            ['user' => $user],
            ['createdAt' => 'DESC'],
            $paginator->getItemsPerPage(),
            $paginator->getCurrentPageFirstItemNumber()
        );

        $view = '@ChillCalendar/Invitations/listByUser.html.twig';

        return $this->render($view, [
            'invitations' => $invitations,
            'paginator' => $paginator,
            'templates' => $this->docGeneratorTemplateRepository->findByEntity(Calendar::class),
        ]);
    }
}
