<?php

namespace OtomaticAi\Content\Faq;

use DOMDocument;
use DOMElement;
use OtomaticAi\Content\Contracts\ShouldDisplay;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class Faq implements ShouldDisplay
{
    public string $hn;
    public array $questions;

    public function __construct(string $hn, array $questions)
    {
        $this->hn = $hn;
        $this->questions = $questions;
    }

    public function toHtmlElement(DOMDocument $document): ?DOMElement
    {
        $el = $document->createElement("otofaq");
        $data = [
            "hn" => $this->hn,
            "questions" => $this->questions,
        ];
        $el->setAttribute("data", base64_encode(json_encode($data)));
        $el->setAttribute("uid", uniqid("faq-"));

        return $el;
    }

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

    static public function fromHtmlElement(DOMElement $node)
    {
        $data = json_decode(base64_decode($node->getAttribute("data")), true);
        $hn = Arr::get($data, "hn", "h3");
        $questions = Arr::get($data, "questions", []);

        return new self($hn, $questions);
    }
}
