<?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\Entity\Edition;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\EditionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

#[Route('/angebote')]
final class OfferCalendarController extends AbstractController
{
    #[Route('/kalender', name: 'admin_offers_calendar')]
    #[Route('/{edition}/kalender', name: 'admin_offers_calendar_in_edition', requirements: ['edition' => '[a-zA-Z0-9_\-+]+'])]
    public function index(
        ?string $edition,
        #[CurrentUser]
        User $user,
        Breadcrumb $breadcrumb,
        EditionRepository $editions,
        Request $request,
    ): Response {
        $aliases = $edition ? array_values(array_filter(explode('+', $edition))) : [];
        $selectedEditions = $aliases ? $editions->findBy(['alias' => $aliases]) : [];
        if ($aliases && \count($selectedEditions) !== \count($aliases)) {
            throw $this->createNotFoundException();
        }

        $allEditions = $editions->findBy([], ['createdAt' => 'DESC']);
        $allEditions = $this->visibleEditions($allEditions, $user);

        $singleEdition = 1 === \count($selectedEditions) ? $selectedEditions[0] : null;

        return $this->render('@FerienpassAdmin/page/offers/calendar.html.twig', [
            'edition' => $singleEdition,
            'editions' => $allEditions,
            'selectedEditions' => $selectedEditions,
            'breadcrumb' => $breadcrumb->generate(
                ['offers.title', ['route' => 'admin_offers_index']],
                $singleEdition instanceof Edition ? [$singleEdition->getName(), ['route' => 'admin_offers_index', 'routeParameters' => ['edition' => $singleEdition->getAlias()]]] : null
            ),
        ]);
    }

    /**
     * @param Edition[] $editions
     *
     * @return Edition[]
     */
    private function visibleEditions(array $editions, User $user): array
    {
        if ($this->isGranted('ROLE_ADMIN')) {
            return $editions;
        }
        $userHost = $user->getHosts()->first() ?: null;

        return array_values(array_filter($editions, static fn (Edition $e) => $e->getHosts()->isEmpty() || ($userHost && $e->getHosts()->contains($userHost))));
    }
}
