<?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;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Ferienpass\CoreBundle\Repository\ParticipantRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\UX\Turbo\TurboBundle;

class AdminCreateController extends AbstractController
{
    #[Route('/admin/create-palette-editions', name: 'admin_create_palette_editions')]
    public function editions(EntityManagerInterface $entityManager): Response
    {
        $editions = $entityManager->getRepository(Edition::class)->findAll();

        $editions = array_filter($editions, fn (Edition $edition) => $this->isGranted('offer.create', $edition));

        return $this->render('@FerienpassAdmin/search/_create_palette_editions.html.twig', [
            'editions' => $editions,
        ]);
    }

    #[Route('/admin/create-attendance-component', name: 'admin_attendance_create_component')]
    public function attendanceComponent(Request $request, OfferRepositoryInterface $offerRepository, ParticipantRepositoryInterface $participantRepository): Response
    {
        $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

        $offer = null;
        $participant = null;

        $referer = $request->headers->get('referer');
        if ($referer) {
            $path = (string) parse_url($referer, \PHP_URL_PATH);
            if (preg_match('#/angebote/([a-f0-9-]+)#', $path, $matches)) {
                $offer = $offerRepository->findByUuid($matches[1]);
            }
            if (preg_match('#/teilnehmende/([a-f0-9-]+)#', $path, $matches)) {
                $participant = $participantRepository->findByUuid($matches[1]);
            }
        }

        return $this->render('@FerienpassAdmin/search/_create_attendance.html.twig', [
            'offer' => $offer,
            'participant' => $participant,
        ]);
    }
}
