<?php

namespace OtomaticAi\Content\Amazon;

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

class Amazon implements ShouldDisplay
{
    public string $template;
    public array $products;

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

    public function toHtmlElement(DOMDocument $document): ?DOMElement
    {
        $el = $document->createElement("otoamazon");
        $data = [
            "template" => $this->template,
            "products" => $this->products,
        ];
        $el->setAttribute("data", base64_encode(json_encode($data)));
        $el->setAttribute("uid", uniqid("amazon-"));

        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);
        $template = Arr::get($data, "template", "grid_3x");
        $products = Arr::get($data, "products", []);

        return new self($template, $products);
    }
}
