<?php declare(strict_types=1);
/*
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Form;

use App\Validator\Recaptcha;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Event\PreSubmitEvent;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class RecaptchaType
 *
 * Reads the Google reCAPTCHA v3 token from the raw POST field
 * `g-recaptcha-response` (populated by JS before form submit) and injects
 * it as this field's value before validation runs.
 *
 * @package  App\Form
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 12.
 */
class RecaptchaType extends AbstractType
{
    public function __construct(private readonly RequestStack $requestStack) {}

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (PreSubmitEvent $event): void {
            $request = $this->requestStack->getCurrentRequest();
            $token   = $request?->request->getString('g-recaptcha-response') ?? '';
            // For forms that set the token directly on the field (e.g. registration_form[recaptcha])
            // rather than via a standalone g-recaptcha-response input, fall back to the submitted value.
            if ($token === '') {
                $token = (string) ($event->getData() ?? '');
            }
            $event->setData($token);
        });
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'mapped'      => false,
            'constraints' => [new Recaptcha()],
        ]);
    }

    public function getParent(): string
    {
        return HiddenType::class;
    }
}