<?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 Doctrine\ORM\EntityManagerInterface;
use Ferienpass\AdminBundle\Breadcrumb\Breadcrumb;
use Ferienpass\AdminBundle\Controller\TagsResponses;
use Ferienpass\AdminBundle\Form\HandleFormTrait;
use Ferienpass\AdminBundle\Form\PersonalDataType;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\HttpCache\CacheTag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

#[Route('/persönliche-daten', name: 'admin_user_index')]
final class PersonalDataController extends AbstractController
{
    use HandleFormTrait;
    use TagsResponses;

    /**
     * Both sections live on one page but each has its own form + save button
     * (matches the cms-bundle account pattern). We instantiate one
     * PersonalDataType per section with `display_section` so only that
     * section's fields are bound/persisted — clicking save on one card
     * doesn't touch the other section's values, even if the user touched
     * fields in both before submitting.
     */
    public function __invoke(#[CurrentUser] User $user, Request $request, EventDispatcherInterface $dispatcher, EntityManagerInterface $entityManager, FormFactoryInterface $formFactory, Breadcrumb $breadcrumb): Response
    {
        $forms = [
            'personal' => $this->createSectionForm($formFactory, $user, 'personal'),
            'public' => $this->createSectionForm($formFactory, $user, 'public'),
        ];

        foreach ($forms as $form) {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $this->handleSubmit($form, $dispatcher, $request);
                $entityManager->flush();

                $this->addFlash('success', 'Die Änderungen wurden erfolgreich übernommen.');

                return $this->redirectToRoute('admin_user_index');
            }
        }

        $this->tagResponse(CacheTag::user($user));

        return $this->render('@FerienpassAdmin/page/user/index.html.twig', [
            'item' => $user,
            'personalForm' => $forms['personal'],
            'publicForm' => $forms['public'],
            'headline' => 'user.title',
            'breadcrumb' => $breadcrumb->generate('user.title'),
        ]);
    }

    private function createSectionForm(FormFactoryInterface $formFactory, User $user, string $section): FormInterface
    {
        return $formFactory->createNamed('user_'.$section, PersonalDataType::class, $user, [
            'display_section' => $section,
        ]);
    }
}
