<?php

declare(strict_types=1);

namespace App\Framework\View\Processors;

use App\Framework\Template\Parser\DomTemplateParser;
use App\Framework\Template\Processing\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\Loading\TemplateLoader;
use App\Framework\View\RenderContext;

final readonly class IncludeProcessor implements DomProcessor
{
    public function __construct(
        private TemplateLoader    $loader,
        private DomTemplateParser $parser = new DomTemplateParser()
    ) {
    }

    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        foreach ($dom->querySelectorAll('include[file]') as $includeNode) {
            $file = $includeNode->getAttribute('file');

            try {
                $html = $this->loader->load($file);
                $includedDom = $this->parser->parseFile($html);

                $fragment = $dom->createDocumentFragment();
                foreach ($includedDom->documentElement->childNodes as $child) {
                    $fragment->appendChild($dom->importNode($child, true));
                }

                $includeNode->parentNode?->replaceChild($fragment, $includeNode);
            } catch (\Throwable $e) {
                // Optional: Fehlerkommentar ins Template schreiben
                $error = $dom->createComment("Fehler beim Laden von '$file': " . $e->getMessage());
                $includeNode->parentNode?->replaceChild($error, $includeNode);
            }
        }

        return $dom;
    }
}
