<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Setup\Converters;

use Magento\Framework\DB\DataConverter\DataConverterInterface;
use Magento\PageBuilder\Model\Dom\Element;
use Magento\PageBuilder\Model\Dom\HtmlDocumentFactory;

/**
 *
 */
class SliderToFiloBluSlider implements DataConverterInterface
{
    /**
     * @var \Magento\PageBuilder\Model\Dom\HtmlDocumentFactory
     */
    private $documentFactory;

    // HtmlDocumentInterface introduced in 1.3.0
    // https://github.com/magento/magento2-page-builder/blob/v1.3.0/app/code/Magento/PageBuilder/Model/Dom/Adapter/HtmlDocumentInterface.php
    /**
     * @param \Magento\PageBuilder\Model\Dom\HtmlDocumentFactory $documentFactory
     */
    public function __construct(HtmlDocumentFactory $documentFactory)
    {
        $this->documentFactory = $documentFactory;
    }

    /**
     * @param $data
     * @return string|null
     */
    public function convert($data): ?string
    {
        $document = $this->documentFactory->create(['document' => $data]);
        $body = $document->querySelector('body');

        /** @var \Magento\PageBuilder\Model\Dom\Element $slider */
        foreach ($document->querySelectorAll('[data-slider-template]') as $slider) {
            if ($slider->getAttribute('data-content-type') !== 'slider') {
                continue;
            }

            $slider->setAttribute('data-content-type', 'filoblu_slider');

            foreach ($slider->querySelectorAll('[data-content-type=slide]') as $slide) {
                $slide->setAttribute('data-content-type', 'filoblu_slide');
            }
        }

        if (method_exists(Element::class, 'getOriginalElement')) {
            $body->appendChild($document->querySelector('style'));
        }

        return $document->stripHtmlWrapperTags();
    }
}
