<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Controller\Page;

use Ferienpass\AdminBundle\Breadcrumb\Breadcrumb;
use Ferienpass\CoreBundle\Repository\SentMessageRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;
use FOS\HttpCacheBundle\Http\SymfonyResponseTagger;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_ADMIN')]
#[Route('/email-probleme')]
class EmailDeliveryErrors extends AbstractController
{
    public function __construct(private readonly UserRepository $users)
    {
    }

    #[Route('', name: 'email_delivery_errors')]
    public function engagement(Breadcrumb $breadcrumb, SentMessageRepository $sentMessageRepository, SymfonyResponseTagger $responseTagger): Response
    {
        $messages = $sentMessageRepository->findWithError();
        foreach ($messages as $message) {
            $responseTagger->addTags(['sentMessage-'.$message->getId()]);
        }

        return $this->render('@FerienpassAdmin/page/tools/email_delivery_errors.html.twig', [
            'numberBlocked' => $this->blockedAccounts()->select('COUNT(user)')->getQuery()->getSingleScalarResult(),
            'messages' => $messages,
            'breadcrumb' => $breadcrumb->generate('tools.title', 'email_delivery_errors.title'),
        ]);
    }

    #[Route('/abgemeldete-kontakte', name: 'blocked_contacts')]
    public function blockedContacts(Breadcrumb $breadcrumb): Response
    {
        return $this->render('@FerienpassAdmin/page/tools/blocked_contacts.html.twig', [
            'qb' => $this->blockedAccounts(),
            'breadcrumb' => $breadcrumb->generate('tools.title', 'email_delivery_errors.title'),
        ]);
    }

    private function blockedAccounts()
    {
        return $this->users->createQueryBuilder('user')
            ->where('user.blockedEmail = 1');
    }
}
