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

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Repository\AttendanceStashRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(route: 'live_component_admin')]
class MoveToStash extends AbstractController
{
    use DefaultActionTrait;

    #[LiveProp]
    public array $attendanceIds = [];

    public string $message = '';

    public function __construct(private readonly AttendanceStashRepository $stashRepository, private readonly AttendanceRepository $attendanceRepository, private readonly EntityManagerInterface $entityManager)
    {
    }

    public function getStashes(): array
    {
        return $this->stashRepository->findAll();
    }

    #[LiveAction]
    public function move(#[LiveArg] int $stashId): void
    {
        $targetStash = $this->stashRepository->find($stashId);
        if (!$targetStash) {
            return;
        }

        $oldStash = null;
        foreach ($this->attendanceIds as $id) {
            $attendance = $this->attendanceRepository->find($id);
            if ($attendance) {
                $oldStash = $attendance->getStash();
                $targetStash->addAttendance($attendance);
            }
        }

        $this->entityManager->flush();

        if ($oldStash && $oldStash->getAttendances()->isEmpty()) {
            $this->entityManager->remove($oldStash);
            $this->entityManager->flush();
        }

        $this->message = 'Anmeldungen wurden verschoben.';
    }
}
