<?php

namespace OtomaticAi\Content;

use DOMDocument;
use DOMElement;
use OtomaticAi\Content\Contracts\ShouldDisplay;

class CustomHtml implements ShouldDisplay
{
    public $html;

    public function __construct($html)
    {
        $this->html = $html;
    }

    public function toHtmlElement(DOMDocument $document): ?DOMElement
    {
        $el = $document->createElement("otocustomhtml");

        $data = [
            "html" => $this->html,
        ];
        
        $el->setAttribute("data", base64_encode(json_encode($data)));

        return $el;
    }

    public function toDisplayElement(DOMElement $node): ?DOMElement
    {
        return $this->toHtmlElement($node->ownerDocument);
    }

    static public function fromHtmlElement(DOMElement $node)
    {
        $html = '';

        foreach ($node->childNodes as $child) {
            $html .= $node->ownerDocument->saveHTML($child);
        }

        return new self($html);
    }
}
