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

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CmsBundle\Form\UserPersonalDataType;
use Ferienpass\CoreBundle\Entity\PostalAddress;
use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\LiveCollectionTrait;

#[AsLiveComponent(template: '@Contao/components/user_personal_data.html.twig', route: 'live_component_cms')]
class UserPersonalData extends AbstractController
{
    use ComponentWithFormTrait;
    use DefaultActionTrait;
    use LiveCollectionTrait;

    public function __construct(private readonly Security $security, #[Autowire(env: 'MAPBOX_TOKEN')] private readonly string $mapboxToken = '')
    {
    }

    public function mapboxToken(): string
    {
        return $this->mapboxToken;
    }

    #[LiveAction]
    public function save(EntityManagerInterface $entityManager): RedirectResponse
    {
        $this->submitForm();

        $entityManager->flush();

        return $this->redirectToRoute('user_account', [
            'alias' => 'account',
        ]);
    }

    protected function instantiateForm(): FormInterface
    {
        $user = $this->security->getUser();

        // Adding addresses is disabled, so seed one empty row for members who
        // have none yet (an untouched row is dropped again on save).
        if ($user instanceof User && 0 === $user->getPostalAddresses()->count()) {
            $user->addPostalAddress(new PostalAddress());
        }

        return $this->createForm(UserPersonalDataType::class, $user);
    }
}
