<?php

declare(strict_types=1);

namespace App\Framework\View;

use Dom\Element;

final readonly class DomFormService
{
    public function addCsrfTokenToForms(DomWrapper $dom, string $token): void
    {
        $forms = $dom->getElementsByTagName('form');

        $forms->forEach(function ($form) use ($dom, $token) {
            $this->addCsrfTokenToForm($dom, $form, $token);
        });
    }

    public function addCsrfTokenToForm(DomWrapper $dom, Element $form, string $token): void
    {
        // Prüfen ob bereits vorhanden
        $existing = $form->querySelector('input[name="_token"]');
        if ($existing) {
            $existing->setAttribute('value', $token);

            return;
        }

        $csrf = $dom->document->createElement('input');
        $csrf->setAttribute('type', 'hidden');
        $csrf->setAttribute('name', '_token');
        $csrf->setAttribute('value', $token);

        $form->insertBefore($csrf, $form->firstChild);
    }

    public function addHoneypotField(DomWrapper $dom, Element $form, string $fieldName = 'email_confirm'): void
    {
        $honeypot = $dom->document->createElement('input');
        $honeypot->setAttribute('type', 'text');
        $honeypot->setAttribute('name', $fieldName);
        $honeypot->setAttribute('style', 'display:none;position:absolute;left:-9999px;');
        $honeypot->setAttribute('tabindex', '-1');
        $honeypot->setAttribute('autocomplete', 'off');

        $form->insertBefore($honeypot, $form->firstChild);
    }
}
