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

use Chill\ActivityBundle\Entity\Activity;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\HttpFoundation\RequestStack;

class ListenToActivityCreate
{
    public function __construct(private readonly RequestStack $requestStack) {}

    public function postPersist(Activity $activity, LifecycleEventArgs $event): void
    {
        // Get the calendarId from the request
        $request = $this->requestStack->getCurrentRequest();

        if (null === $request) {
            return;
        }

        if ($request->query->has('activityData')) {
            $activityData = $request->query->all('activityData');

            if (\array_key_exists('calendarId', $activityData)) {
                $calendarId = $activityData['calendarId'];

                // Attach the activity to the calendar
                $em = $event->getObjectManager();

                $calendar = $em->getRepository(\Chill\CalendarBundle\Entity\Calendar::class)->find($calendarId);
                $calendar->setActivity($activity);

                $em->persist($calendar);
                $em->flush();
            }
        }
    }
}
