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

use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class UserRegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('firstname', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                ],
            ])
            ->add('lastname', TextType::class, [
                'constraints' => [
                    new NotBlank(),
                ],
            ])
            ->add('email', EmailType::class, [
                'attr' => [
                    'placeholder' => 'email@beispiel.de',
                ],
                'constraints' => [
                    new NotBlank(),
                    new Email(),
                ],
            ])
            ->add('method', HiddenType::class, [
                'mapped' => false,
                'data' => 'passkey',
                'empty_data' => 'passkey',
            ])
            ->add('plainPassword', PasswordType::class, [
                'hash_property_path' => 'password',
                'mapped' => false,
                'always_empty' => false,
                'required' => false,
                'help' => 'Ihr Passwort muss aus mindestens 8 Zeichen bestehen.',
                'constraints' => [
                    new NotBlank(groups: ['with_password']),
                    new Length(min: 8, groups: ['with_password']),
                ],
            ])
        ;

        if ($options['ask_mobile']) {
            $builder
                ->add('mobile', TelType::class, [
                    'constraints' => [
                        new PhoneNumber(type: PhoneNumber::MOBILE, defaultRegion: 'DE'),
                        new Callback(static function (mixed $value, ExecutionContextInterface $context, mixed $payload): void {
                            /** @var FormInterface $form */
                            $form = $context->getRoot();
                            if (!$form->has('phone') || !$form->has('mobile')) {
                                return;
                            }

                            if ($form->get('phone')->isEmpty() && $form->get('mobile')->isEmpty()) {
                                $context->buildViolation('registration.phoneOrMobileValidation')
                                    ->setTranslationDomain('cms')
                                    ->atPath('mobile')
                                    ->addViolation();
                            }
                        }),
                    ],
                    'attr' => [
                        'placeholder' => '0172-0000000',
                    ],
                    'required' => false,
                ])
            ;
        }

        if ($options['ask_phone']) {
            $builder
                ->add('phone', TelType::class, [
                    'constraints' => [
                        new PhoneNumber(type: PhoneNumber::FIXED_LINE, defaultRegion: 'DE'),
                        new Callback(static function (mixed $value, ExecutionContextInterface $context, mixed $payload): void {
                            /** @var FormInterface $form */
                            $form = $context->getRoot();
                            if (!$form->has('phone') || !$form->has('mobile')) {
                                return;
                            }

                            if ($form->get('phone')->isEmpty() && $form->get('mobile')->isEmpty()) {
                                $context->buildViolation('registration.phoneOrMobileValidation')
                                    ->setTranslationDomain('cms')
                                    ->atPath('phone')
                                    ->addViolation();
                            }
                        }),
                    ],
                    'attr' => [
                        'placeholder' => '030-00000',
                    ],
                    'required' => false,
                ])
            ;
        }
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'mapped' => false,
            'label_format' => 'registration.%name%',
            'translation_domain' => 'cms',
            'ask_phone' => true,
            'ask_mobile' => true,
            'csrf_protection' => false,
            'validation_groups' => static function (FormInterface $form): array {
                $method = $form->has('method') ? (string) $form->get('method')->getData() : 'password';

                return 'passkey' === $method ? ['Default'] : ['Default', 'with_password'];
            },
        ]);

        $resolver->setAllowedTypes('ask_phone', 'bool');
        $resolver->setAllowedTypes('ask_mobile', 'bool');
    }
}
