<?php

namespace App\Framework\View\Processors;

use App\Framework\Meta\OpenGraphType;
use App\Framework\View\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use Dom\HTMLDocument;

final readonly class MetaManipulator implements DomProcessor
{
    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        $description = $context->metaData->description;


        $dom->document->head->querySelector('meta[name="description"]')?->setAttribute('content', $description);

        if($dom->document->head->getElementsByTagName('title')->item(0)) {
            $dom->document->head->getElementsByTagName('title')->item(0)->textContent = $context->metaData->title . " | Michael Schiemer";
        }


        match($context->metaData->openGraph->type)
        {
            OpenGraphType::WEBSITE => $dom->document->head->querySelector('meta[property="og:type"]')?->setAttribute('content', 'website'),
            default => throw new \Exception('Unexpected match value'),
        };


        foreach ($dom->document->querySelectorAll('meta[name][content]') as $meta) {
            $name = $meta->getAttribute('name');
            $content = $meta->getAttribute('content');


            #debug($name);

            // Wenn Variable bereits im Context gesetzt ist, nicht überschreiben
            #if (!array_key_exists($name, $context->data)) {
            #    $context->data[$name] = $content;
            #}
        }

        return $dom;
    }
}
