<?php

namespace App\Framework\View;

final readonly class DomHeadService
{
    public function appendToHead(DomWrapper $dom, string $html): void {
        $head = $dom->getElementsByTagName('head')->first();
        if (!$head) {
            // Fallback: head erstellen oder zu body hinzufügen
            $head = $dom->document->createElement('head');
            $dom->document->documentElement->insertBefore($head, $dom->document->body);
        }

        $fragment = $dom->createFragmentFromHtml($html);
        $head->appendChild($fragment);
    }

    public function prependToHead(DomWrapper $dom, string $html): void {
        $head = $dom->getElementsByTagName('head')->first();
        if (!$head) return;

        $fragment = $dom->createFragmentFromHtml($html);
        $head->insertBefore($fragment, $head->firstChild);
    }

    public function addStylesheet(DomWrapper $dom, string $href): void {
        $link = $dom->document->createElement('link');
        $link->setAttribute('rel', 'stylesheet');
        $link->setAttribute('href', $href);

        $head = $dom->getElementsByTagName('head')->first();
        $head?->appendChild($link);
    }

    public function addScript(DomWrapper $dom, string $src, array $attributes = []): void {
        $script = $dom->document->createElement('script');
        $script->setAttribute('src', $src);
        $script->setAttribute('type', 'module');

        foreach ($attributes as $name => $value) {
            $script->setAttribute($name, $value);
        }

        $head = $dom->getElementsByTagName('head')->first();
        $head?->appendChild($script);
    }

    public function addMeta(DomWrapper $dom, string $name, string $content): void {
        $meta = $dom->document->createElement('meta');
        $meta->setAttribute('name', $name);
        $meta->setAttribute('content', $content);

        $head = $dom->getElementsByTagName('head')->first();
        $head?->appendChild($meta);
    }
}
