<?php

namespace App\Framework\View\Processors;

use App\Framework\DI\Container;
use App\Framework\Meta\MetaData;
use App\Framework\View\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use App\Framework\View\TemplateProcessor;

final class ForProcessor implements DomProcessor
{
    public function __construct(
        private Container $container,
        private ?TemplateProcessor $templateProcessor = null,

    ) {
        // Falls kein TemplateProcessor übergeben wird, erstellen wir einen mit den Standard-Prozessoren
        if ($this->templateProcessor === null) {
            #$this->templateProcessor = new TemplateProcessor([],[PlaceholderReplacer::class], $this->container);
            #$this->templateProcessor->register(PlaceholderReplacer::class);
            $this->templateProcessor = $this->container->get(TemplateProcessor::class);
        }
    }

    /**
     * @inheritDoc
     */
    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        foreach ($dom->document->querySelectorAll('for[var][in]') as $node) {
            $var = $node->getAttribute('var');
            $in = $node->getAttribute('in');

            $output = '';

            $items = $context->data[$in] ?? null;
            if (isset($context->model->{$in}) && $items === null) {
                $items = $context->model->{$in};
            }

            if (is_iterable($items)) {
                foreach ($items as $item) {
                    $clone = $node->cloneNode(true);

                    // Neuen Kontext für die Schleifenvariable erstellen
                    $loopContext = new RenderContext(
                        template: $context->template,
                        metaData: new MetaData('', ''),
                        data: array_merge($context->data, [$var => $item]),
                        #model: $context->model,
                        controllerClass: $context->controllerClass
                    );

                    // Den Inhalt der Schleife mit den bestehenden Prozessoren verarbeiten
                    $innerHTML = $clone->innerHTML;

                    $processedContent = $this->templateProcessor->render($loopContext, $innerHTML, true);

                    $output .= $processedContent;
                }
            }

            $replacement = $dom->document->createDocumentFragment();
            @$replacement->appendXML($output);
            $node->parentNode?->replaceChild($replacement, $node);
        }

        return $dom;
    }
}
