<?php

/**
 * Block Converter.
 * Convert HTML to Gutenberg Blocks.
 *
 * @see https://github.com/tyme-labs/block-converter
 */

namespace OtomaticAi\Utils;

use DOMDocument;
use DOMElement;
use Exception;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\Illuminate\Support\Str;

/* phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase */

class Gutemberg
{

    /**
     * Block Converter Options.
     *
     * @var array
     */
    public $options = [
        'upload_media' => true,
        'force_https'  => false,
        'auto_p'       => true,
        'title' => "image",
    ];

    /**
     * Raw content provided
     *
     * @var string
     */
    private $raw_content = '';

    /**
     * Dom document
     *
     * @var DOMDocument
     */
    private $dom_content = '';

    /**
     * Processed block content
     *
     * @var string
     */
    private $block_content = '';

    /**
     * A readable list of allowed tags and attributes.
     * "class" and "id" are always allowed and do not need to be defined.
     *
     * @var array
     */
    private $allowed_tags = [
        // Content Sectioning
        'h1'         => [],
        'h2'         => [],
        'h3'         => [],
        'h4'         => [],
        'h5'         => [],
        'h6'         => [],

        // Text Content
        'blockquote' => [],
        'dd'         => [],
        'dt'         => [],
        'dl'         => [],
        'figcaption' => [],
        'figure'     => [],
        'hr'         => [],
        'li'         => [],
        'ul'         => [
            'type',
        ],
        'ol'         => [
            'reversed',
            'start',
            'type',
        ],
        'p'          => [],

        // Inline text semantics
        'a'          => [
            'href',
            'target',
            'title',
            'rel',
        ],
        'abbr'       => [
            'title',
        ],
        'b'          => [],
        'br'         => [],
        'cite'       => [],
        'code'       => [],
        'em'         => [],
        'i'          => [],
        's'          => [],
        'strike'     => [],
        'small'      => [],
        'span'       => [],
        'strong'     => [],
        'sub'        => [],
        'sup'        => [],

        // Image and multimedia
        'audio'      => [
            'src',
            'controls',
            'autoplay',
        ],
        'img'        => [
            'src',
            'alt',
            'srcset',
            'height',
            'width',
            'sizes',
        ],
        'video'      => [
            'src',
            'controls',
            'autoplay',
            'poster',
        ],

        // Embedded content
        'embed'      => [
            'src',
            'height',
            'width',
            'type',
        ],
        'iframe'     => [
            'src',
            'height',
            'width',
        ],
        'object'     => [],
        'picture'    => [],
        'portal'     => [
            'src',
        ],
        'pre'        => [],
        'source'     => [
            'type',
            'src',
            'alt',
            'srcset',
            'height',
            'width',
            'sizes',
            'media',
        ],

        // Table content
        'caption'    => [],
        'col'        => [
            'span',
        ],
        'colgroup'   => [
            'span',
        ],
        'table'      => [],
        'tbody'      => [],
        'td'         => [
            'colspan',
            'headers',
            'rowspan',
        ],
        'tfoot'      => [],
        'th'         => [
            'abbr',
            'colspan',
            'headers',
            'rowspan',
        ],
        'thead'      => [],
        'tr'         => [],

        // custom
        'otoimage' => [
            "attachment" => true,
            "provider" => true,
        ],
        'otoyoutube' => [
            "videoid" => true,
        ],
        'otoinstagram' => [
            "href" => true,
        ],
        'otoamazon' => [
            "data" => true,
        ],
        'otofaq' => [
            "data" => true,
        ],
        'otofacebook' => [
            "href" => true,
        ],
        'ototiktok' => [
            "href" => true,
        ],
        'ototwitter' => [
            "href" => true,
        ],
        'otocustomhtml' => [],
    ];

    /**
     * Dom Element Block Mapping
     *
     * @var array
     */
    private $mapping = [
        'p'          => 'core/paragraph',
        'code'       => [__CLASS__, 'code'],
        'pre'        => [__CLASS__, 'code'],
        'ul'         => [__CLASS__, 'list'],
        'table'      => [__CLASS__, 'table'],
        'ol'         => [__CLASS__, 'ordered_list'],
        'h1'         => [__CLASS__, 'heading'],
        'h2'         => [__CLASS__, 'heading'],
        'h3'         => [__CLASS__, 'heading'],
        'h4'         => [__CLASS__, 'heading'],
        'h5'         => [__CLASS__, 'heading'],
        'h6'         => [__CLASS__, 'heading'],
        'blockquote' => [__CLASS__, 'blockquote'],
        'img'        => [__CLASS__, 'image'],
        'hr'         => [__CLASS__, 'hr'],
        'otoimage'   => [__CLASS__, 'otoimage'],
        'otoyoutube' => [__CLASS__, 'otoyoutube'],
        'otoinstagram' => [__CLASS__, 'otoinstagram'],
        'otoamazon' => [__CLASS__, 'otoamazon'],
        'otofaq' => [__CLASS__, 'otofaq'],
        'otofacebook' => [__CLASS__, 'otofacebook'],
        'ototiktok' => [__CLASS__, 'ototiktok'],
        'ototwitter' => [__CLASS__, 'ototwitter'],
        'otocustomhtml' => [__CLASS__, 'otocustomhtml'],
    ];

    /**
     * BlockConverter constructor.
     *
     * @param array $options Options.
     */
    public function __construct($options = [])
    {
        $this->options      = wp_parse_args($options, $this->options);
        $this->mapping      = $this->get_mapping();
        $this->allowed_tags = $this->get_allowed_tags();
    }

    /**
     * Convert HTML to Block Markup
     *
     * @param string $content Post Content to Convert.
     */
    public function convert_blocks(string $content = '')
    {
        $this->load_content($content);
        $this->convert_to_blocks();

        return $this->render();
    }

    /**
     * BlockConverter load HTML.
     *
     * @param string $html post content
     */
    public function load_content(string $html)
    {
        if (substr($html, 0, 1) !== '<') {
            $html = '<html><body>' . $html . '</body></html>';
        }

        $this->block_content = '';
        $this->raw_content   = $html;
        $this->dom_content   = new DOMDocument();

        $encoded = mb_convert_encoding(stripslashes($html), 'HTML-ENTITIES', 'UTF-8');
        if (false !== $this->options['auto_p']) {
            $encoded = $this->wpautop($encoded);
        }

        // phpcs:ignore
        libxml_use_internal_errors(true);
        @$this->dom_content->loadHTML($this->clean_content($encoded), LIBXML_NOWARNING);
        libxml_use_internal_errors(false);
    }

    /**
     * Return block rendered content
     *
     * @return string
     */
    public function render()
    {
        if (empty($this->block_content)) {
            return $this->raw_content;
        }

        // Remove paragraphs that are wrapping other blocks.
        $content = $this->block_content;
        $content = preg_replace('/(<!-- wp:paragraph --><p>)(<!--)/i', '$2', $content);
        $content = preg_replace('/(-->)(<\/p><!-- \/wp:paragraph -->)/i', '$1', $content);

        return $content;
    }

    /**
     * Get block mapping
     *
     * @return array
     */
    public function get_mapping()
    {
        /**
         * Filter block converter DOM Mapping.
         *
         * @param array $mapping Mapping
         * @return array
         */
        return apply_filters('block_converter_mapping', $this->mapping);
    }

    /**
     * Add custom DOM mapping.
     * Allows for converting elements to custom blocks.
     *
     * @param string   $dom_element_tag Dom element tag
     * @param callable $mapping         Block callback
     */
    public function add_dom_mapping($dom_element_tag, $mapping)
    {
        $this->mapping[$dom_element_tag] = $mapping;
    }

    /**
     * Remove DOM element mapping
     *
     * @param string $dom_element_tag Dom element tag
     */
    public function remove_dom_mapping($dom_element_tag)
    {
        unset($this->mapping[$dom_element_tag]);
    }

    /**
     * Set converter option
     *
     * @param string $option option name
     * @param mixed  $value  option value
     */
    public function set_option($option, $value)
    {
        $this->options[$option] = $value;
    }

    /**
     * Set converter options
     *
     * @param array $options options
     */
    public function set_options($options = [])
    {
        $this->options = wp_parse_args($options, $this->options);
    }

    /**
     * Get allowed tag and attributes.
     *
     * @return array
     */
    public function get_allowed_tags()
    {
        /**
         * Filter block converter allowed tags.
         *
         * @param array $allowed_tags Allowed tags
         * @return array
         */
        return apply_filters('block_converter_allowed_tags', $this->allowed_tags);
    }

    /**
     * Set allowed tag and attributes.
     *
     * @param string $tag       Tag name
     * @param array  $attributes Tag attributes
     */
    public function add_allowed_tag($tag, $attributes = [])
    {
        $this->allowed_tags[$tag] = $attributes;
    }

    /**
     * Remove unwanted HTML attributes from an element.
     *
     * @param DOMElement $element The element to clean.
     * @return DOMElement
     */
    protected function clean_attributes(DOMElement $element)
    {
        if (! $element->hasAttributes()) {
            return $element;
        }

        // Default allowed attributes.
        $allowed_attributes = [
            'class',
            'id',
        ];

        // Allow adding additional attributes at the tag level.
        if (isset($element->tagName) && ! empty($this->allowed_tags[$element->tagName])) {
            $allowed_attributes = array_merge($allowed_attributes, $this->allowed_tags[$element->tagName]);
        }

        for ($i = $element->attributes->length - 1; $i >= 0; --$i) {
            if (! in_array($element->attributes->item($i)->nodeName, $allowed_attributes, true)) {
                $element->removeAttributeNode($element->attributes->item($i));
            }
        }

        return $element;
    }

    /**
     * Convert DOMDocument elements to blocks
     */
    private function convert_to_blocks()
    {
        if (0 === $this->dom_content->getElementsByTagName('body')->count()) {
            return;
        }

        foreach ($this->dom_content->getElementsByTagName('body')->item(0)->childNodes as $element) {
            $has_tag_mapping = isset($element->tagName) && isset($this->mapping[$element->tagName]);

            if ($has_tag_mapping && ! $this->is_callback($this->mapping[$element->tagName])) {
                $this->block_content .= $this->serialize_block(
                    [
                        'blockName' => $this->mapping[$element->tagName],
                        'attrs'     => [],
                        'innerHTML' => $this->get_html($element),
                    ]
                );
                $this->block_content .= "\n\n";
            } elseif ($has_tag_mapping && $this->is_callback($this->mapping[$element->tagName])) {
                $this->block_content .= $this->serialize_block(call_user_func($this->mapping[$element->tagName], $element));
                $this->block_content .= "\n\n";
            } elseif (! $has_tag_mapping && ! empty(preg_replace('/[^a-z_\-0-9]/i', '', $element->textContent)) && false === strpos($element->textContent, '[')) {
                $this->block_content .= $this->serialize_block(
                    [
                        'blockName' => 'core/paragraph',
                        'attrs'     => [],
                        'innerHTML' => '<p>' . trim($this->get_html($element)) . '</p>',
                    ]
                );

                $this->block_content .= "\n\n";
            } elseif (isset($element->tagName)) {
                $this->block_content .= $this->serialize_block(
                    [
                        'blockName' => 'core/html',
                        'attrs'     => [],
                        'innerHTML' => $this->get_html($element),
                    ]
                );
                $this->block_content .= "\n\n";
            } elseif (false !== strpos($element->textContent, '[')) {
                $this->block_content .= $element->textContent;
            }
        }
    }

    /**
     * Clean content for post.
     * We use our own allowed tags and attributes for any custom markup.
     * The rest comes from the default wp_kses_post() tags.
     *
     * @param string $content The content.
     * @return string
     */
    protected function clean_content($content)
    {
        // $allowed_tags = wp_kses_allowed_html('post');
        // $allowed_tags = wp_parse_args($allowed_tags, $this->allowed_tags);

        // return wp_kses($content, $allowed_tags);

        return $content;
    }

    /**
     * Custom wpautop
     * 
     * @param string $text
     * @param boolean $br
     * @return string
     */
    private function wpautop($text, $br = true)
    {
        $pre_tags = array();

        if (trim($text) === '') {
            return '';
        }

        // Just to make things a little easier, pad the end.
        $text = $text . "\n";

        /*
         * Pre tags shouldn't be touched by autop.
         * Replace pre tags with placeholders and bring them back after autop.
         */
        if (Str::contains($text, '<pre')) {
            $text_parts = explode('</pre>', $text);
            $last_part  = array_pop($text_parts);
            $text       = '';
            $i          = 0;

            foreach ($text_parts as $text_part) {
                $start = strpos($text_part, '<pre');

                // Malformed HTML?
                if (false === $start) {
                    $text .= $text_part;
                    continue;
                }

                $name              = "<pre wp-pre-tag-$i></pre>";
                $pre_tags[$name] = substr($text_part, $start) . '</pre>';

                $text .= substr($text_part, 0, $start) . $name;
                ++$i;
            }

            $text .= $last_part;
        }
        // Change multiple <br>'s into two line breaks, which will turn into paragraphs.
        $text = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $text);

        $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary|otoimage|otoyoutube|otofacebook|ototiktok|ototwitter|otocustomhtml|otoamazon|otofaq)';

        // Add a double line break above block-level opening tags.
        $text = preg_replace('!(<' . $allblocks . '[\s/>])!', "\n\n$1", $text);

        // Add a double line break below block-level closing tags.
        $text = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $text);

        // Add a double line break after hr tags, which are self closing.
        $text = preg_replace('!(<hr\s*?/?>)!', "$1\n\n", $text);

        // Standardize newline characters to "\n".
        $text = str_replace(array("\r\n", "\r"), "\n", $text);

        // Find newlines in all elements and add placeholders.
        $text = wp_replace_in_html_tags($text, array("\n" => ' <!-- wpnl --> '));

        // Collapse line breaks before and after <option> elements so they don't get autop'd.
        if (Str::contains($text, '<option')) {
            $text = preg_replace('|\s*<option|', '<option', $text);
            $text = preg_replace('|</option>\s*|', '</option>', $text);
        }

        /*
	     * Collapse line breaks inside <object> elements, before <param> and <embed> elements
	     * so they don't get autop'd.
	     */
        if (Str::contains($text, '</object>')) {
            $text = preg_replace('|(<object[^>]*>)\s*|', '$1', $text);
            $text = preg_replace('|\s*</object>|', '</object>', $text);
            $text = preg_replace('%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $text);
        }

        /*
	     * Collapse line breaks inside <audio> and <video> elements,
	     * before and after <source> and <track> elements.
	     */
        if (Str::contains($text, '<source') || Str::contains($text, '<track')) {
            $text = preg_replace('%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $text);
            $text = preg_replace('%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $text);
            $text = preg_replace('%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $text);
        }

        // Collapse line breaks before and after <figcaption> elements.
        if (Str::contains($text, '<figcaption')) {
            $text = preg_replace('|\s*(<figcaption[^>]*>)|', '$1', $text);
            $text = preg_replace('|</figcaption>\s*|', '</figcaption>', $text);
        }

        // Remove more than two contiguous line breaks.
        $text = preg_replace("/\n\n+/", "\n\n", $text);

        // Split up the contents into an array of strings, separated by double line breaks.
        $paragraphs = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY);

        // Reset $text prior to rebuilding.
        $text = '';

        // Rebuild the content as a string, wrapping every bit with a <p>.
        foreach ($paragraphs as $paragraph) {
            $text .= '<p>' . trim($paragraph, "\n") . "</p>\n";
        }

        // Under certain strange conditions it could create a P of entirely whitespace.
        $text = preg_replace('|<p>\s*</p>|', '', $text);

        // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
        $text = preg_replace('!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $text);

        // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
        $text = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $text);

        // In some cases <li> may get wrapped in <p>, fix them.
        $text = preg_replace('|<p>(<li.+?)</p>|', '$1', $text);

        // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
        $text = preg_replace('|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $text);
        $text = str_replace('</blockquote></p>', '</p></blockquote>', $text);

        // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
        $text = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', '$1', $text);

        // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
        $text = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $text);

        // Optionally insert line breaks.
        if ($br) {
            // Replace newlines that shouldn't be touched with a placeholder.
            $text = preg_replace_callback('/<(script|style|svg|math).*?<\/\\1>/s', '_autop_newline_preservation_helper', $text);

            // Normalize <br>
            $text = str_replace(array('<br>', '<br/>'), '<br />', $text);

            // Replace any new line characters that aren't preceded by a <br /> with a <br />.
            $text = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $text);

            // Replace newline placeholders with newlines.
            $text = str_replace('<WPPreserveNewline />', "\n", $text);
        }

        // If a <br /> tag is after an opening or closing block tag, remove it.
        $text = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', '$1', $text);

        // If a <br /> tag is before a subset of opening or closing block tags, remove it.
        $text = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $text);
        $text = preg_replace("|\n</p>$|", '</p>', $text);

        // Replace placeholder <pre> tags with their original content.
        if (! empty($pre_tags)) {
            $text = str_replace(array_keys($pre_tags), array_values($pre_tags), $text);
        }

        // Restore newlines in all elements.
        if (Str::contains($text, '<!-- wpnl -->')) {
            $text = str_replace(array(' <!-- wpnl --> ', '<!-- wpnl -->'), "\n", $text);
        }

        return $text;
    }

    /**
     * Heading block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function heading(DOMElement $element)
    {
        return [
            'blockName' => 'core/heading',
            'attrs'     => [
                'level' => (int) preg_replace('/\D/', '', $element->tagName),
            ],
            'innerHTML' => $this->get_html($element),
        ];
    }

    /**
     * Blockquote block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function blockquote(DOMElement $element)
    {
        $element->setAttribute('class', 'wp-block-quote');
        return [
            'blockName' => 'core/quote',
            'attrs'     => [],
            'innerHTML' => $this->get_html($element),
        ];
    }

    /**
     * List block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function list(DOMElement $element)
    {
        $inner_blocks = '';
        foreach ($element->getElementsByTagName('li') as $node) {
            $inner_blocks .= $this->serialize_block($this->list_item($node));
        }

        return [
            'blockName' => 'core/list',
            'innerHTML' => '<ul>' . $inner_blocks . '</ul>',
        ];
    }

    /**
     * Ordered List block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function ordered_list(DOMElement $element)
    {
        $inner_blocks = '';
        foreach ($element->getElementsByTagName('li') as $node) {
            $inner_blocks .= $this->serialize_block($this->list_item($node));
        }

        return [
            'blockName' => 'core/list',
            'attrs'     => [
                'ordered' => true,
            ],
            'innerHTML' => '<ol>' . $inner_blocks . '</ol>',
        ];
    }

    /**
     * List Item block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function list_item(DOMElement $element)
    {
        return [
            'blockName' => 'core/list-item',
            'attrs'     => [],
            'innerHTML' => $this->get_html($element),
        ];
    }

    /**
     * Table block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function table(DOMElement $element)
    {
        return [
            'blockName' => 'core/table',
            'attrs'     => [],
            'innerHTML' => '<figure class="wp-block-table">' . $this->get_html($element) . '</figure>',
        ];
    }

    /**
     * HR block mapping
     *
     * @return array
     */
    private function hr()
    {
        return [
            'blockName' => 'core/separator',
            'attrs'     => [],
            'innerHTML' => '<hr class="wp-block-separator"/>',
        ];
    }

    /**
     * Code block mapping
     *
     * @param DOMElement $element dom element
     * @return array
     */
    private function code(DOMElement $element)
    {
        return [
            'blockName' => 'core/code',
            'attrs'     => [
                'content' => $this->get_html($element),
            ],
            'innerHTML' => '<pre class="wp-block-code">' . $this->get_html($element) . '</pre>',
        ];
    }

    /**
     * Image block mapping
     *
     * @param DOMElement $element dom element
     * @return array|string
     */
    private function image(DOMElement $element)
    {
        // Got to have a URL.
        $img_src = $element->getAttribute('src');
        if (empty($img_src)) {
            return;
        }

        $img_title = $element->getAttribute('title');
        $img_alt   = $this->get_image_alt($element);
        if (empty($img_alt) && ! empty($img_title)) {
            $img_alt = $img_title;
        }

        // If we're uploading media, download the image into the media library.
        // This will return an existing attachment if the slug already exists.
        if (false !== $this->options['upload_media']) {
            $image = $this->upload_image($img_src);

            if (is_wp_error($image)) {
                try {
                    $image = Image::fromUrl($img_src);
                    $title = Str::slug($this->options["title"]);
                    $attachment_id = $image->save($title, $img_alt);
                    $image          = [];
                    $image['ID']    = absint($attachment_id);
                    $image['url']   = wp_get_attachment_url($attachment_id);
                    $image['sizes'] = wp_get_attachment_metadata($attachment_id);
                } catch (Exception $e) {
                    return;
                }
            }
        } else {
            $image = [
                'ID'  => 1,
                'url' => $img_src,
            ];
        }

        // Failed to upload image? Bail.
        if (empty($image) || is_wp_error($image)) {
            return;
        }

        // Get the image URL after upload conditional & maybe force https
        $img_src = $image['url'];
        if (false !== $this->options['force_https']) {
            $img_src = str_ireplace('http://', 'https://', $img_src);
        }

        // Create the image markup
        $img_tag = sprintf(
            '<figure class="wp-block-image"><img src="%1$s" alt="%2$s" class="%3$s" /></figure>',
            esc_url($img_src),
            trim(esc_attr($img_alt)),
            'wp-image-' . $image['ID']
        );

        return [
            'blockName' => 'core/image',
            'attrs'     => [
                'id'              => $image['ID'],
                'url'             => $img_src,
                'alt'             => $img_alt,
                'title'           => $img_title,
                'sizeSlug'        => 'full',
                'linkDestination' => 'none',
            ],
            'innerHTML' => $img_tag,
        ];
    }

    private function otoimage(DOMElement $element)
    {
        // get attachment id
        $attachmentId = $element->getAttribute("attachment");
        if (empty($attachmentId)) {
            return;
        }

        $url = wp_get_attachment_image_url($attachmentId, 'full');
        $alt = get_post_meta($attachmentId, '_wp_attachment_image_alt', true);

        // Create the image markup
        $img_tag = sprintf(
            '<figure class="wp-block-image size-full"><img src="%1$s" alt="%2$s" class="%3$s" /></figure>',
            esc_url($url),
            trim(esc_attr($alt)),
            'wp-image-' . $attachmentId
        );

        return [
            'blockName' => 'core/image',
            'attrs'     => [
                'id'              => $attachmentId,
                'sizeSlug'        => 'full',
                'linkDestination' => 'none',
            ],
            'innerHTML' => $img_tag,
        ];
    }

    private function otoyoutube(DOMElement $element)
    {
        // get attachment id
        $videoid = $element->getAttribute("videoid");
        if (empty($videoid)) {
            return;
        }

        $url = "https://www.youtube.com/watch?v=" . $videoid;

        // Create the video markup
        $videoTag = sprintf(
            "<figure class=\"is-provider-youtube is-type-video wp-block-embed wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n%1\$s\n</div></figure>",
            esc_url($url)
        );

        return [
            'blockName' => 'core-embed/youtube',
            'attrs'     => [
                'url' => $url,
                'type' => 'video',
                'providerNameSlug' => 'youtube',
                'responsive' => true,
                'className' => 'wp-embed-aspect-16-9 wp-has-aspect-ratio',
            ],
            'innerHTML' => $videoTag,
        ];
    }

    private function otoamazon(DOMElement $element)
    {
        // get data
        $data = $element->getAttribute("data");

        $data = base64_decode($data);
        $data = json_decode($data, true);
        if (empty($data)) {
            return;
        }

        // template
        $template = Arr::get($data, "template", "grid_3x");

        // products
        $products = Arr::get($data, "products", []);

        if (empty($products)) {
            return;
        }

        // shortcode
        $shortcode = sprintf(
            '[otomatic-ai-amazon-products template="%s" products="%s"]',
            esc_attr($template),
            base64_encode(json_encode($products))
        );

        // create the gutenberg core/shortcode block
        $block = [
            'blockName' => 'core/shortcode',
            'attrs'     => [],
            'innerHTML' => $shortcode,
        ];

        return $block;
    }

    private function otofaq(DOMElement $element)
    {
        // get data
        $data = $element->getAttribute("data");

        $data = base64_decode($data);
        $data = json_decode($data, true);
        if (empty($data)) {
            return;
        }

        // template
        $hn = Arr::get($data, "hn", "h3");

        // questions
        $questions = Arr::get($data, "questions", []);

        if (empty($questions)) {
            return;
        }
        
        $htmlParts = [];

        // schema.org
        $schema = [
            "@context" => "https://schema.org",
            "@type" => "FAQPage",
            "mainEntity" => [],
        ];
        foreach ($questions as $question) {
            $schema["mainEntity"][] = [
                "@type" => "Question",
                "name" => Arr::get($question, "title", ""),
                "acceptedAnswer" => [
                    "@type" => "Answer",
                    "text" => Arr::get($question, "description", ""),
                ],
            ];
        }

        $htmlParts[] = "<script type=\"application/ld+json\">";
        $htmlParts[] = json_encode($schema);
        $htmlParts[] = "</script>";

        // faq
        foreach ($questions as $question) {
            $title = Arr::get($question, "title", "");
            $description = Arr::get($question, "description", "");
            
            $htmlParts[] = "<{$hn}>{$title}</{$hn}>";
            $htmlParts[] = "<p>{$description}</p>";
        }

        // create the gutenberg core/html block
        $block = [
            'blockName' => 'core/html',
            'attrs'     => [],
            'innerHTML' => implode("\n", $htmlParts),
        ];

        return $block;
    }

    private function otoinstagram(DOMElement $element)
    {
        // get href
        $href = $element->getAttribute("href");
        if (empty($href)) {
            return;
        }

        // Create the html markup
        $html = [];
        $html[] = '<blockquote class="instagram-media" data-instgrm-captioned data-instgrm-permalink="' . esc_url($href) . '" data-instgrm-version="14" style="background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:540px; min-width:326px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);">';
        $html[] = '<div style="padding:16px;">';
        $html[] = '<a href="' . esc_url($href) . '" style=" background:#FFFFFF; line-height:0; padding:0 0; text-align:center; text-decoration:none; width:100%;" target="_blank">';
        $html[] = '<div style=" display: flex; flex-direction: row; align-items: center;">';
        $html[] = '<div style="background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 40px; margin-right: 14px; width: 40px;"></div>';
        $html[] = '<div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center;">';
        $html[] = '<div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 100px;"></div>';
        $html[] = '<div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 60px;"></div>';
        $html[] = '</div>';
        $html[] = '</div>';
        $html[] = '<div style="padding: 19% 0;"></div>';
        $html[] = '<div style="display:block; height:50px; margin:0 auto 12px; width:50px;">';
        $html[] = '<svg width="50px" height="50px" viewBox="0 0 60 60" version="1.1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink">';
        $html[] = '<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">';
        $html[] = '<g transform="translate(-511.000000, -20.000000)" fill="#000000">';
        $html[] = '<g>';
        $html[] = '<path d="M556.869,30.41 C554.814,30.41 553.148,32.076 553.148,34.131 C553.148,36.186 554.814,37.852 556.869,37.852 C558.924,37.852 560.59,36.186 560.59,34.131 C560.59,32.076 558.924,30.41 556.869,30.41 M541,60.657 C535.114,60.657 530.342,55.887 530.342,50 C530.342,44.114 535.114,39.342 541,39.342 C546.887,39.342 551.658,44.114 551.658,50 C551.658,55.887 546.887,60.657 541,60.657 M541,33.886 C532.1,33.886 524.886,41.1 524.886,50 C524.886,58.899 532.1,66.113 541,66.113 C549.9,66.113 557.115,58.899 557.115,50 C557.115,41.1 549.9,33.886 541,33.886 M565.378,62.101 C565.244,65.022 564.756,66.606 564.346,67.663 C563.803,69.06 563.154,70.057 562.106,71.106 C561.058,72.155 560.06,72.803 558.662,73.347 C557.607,73.757 556.021,74.244 553.102,74.378 C549.944,74.521 548.997,74.552 541,74.552 C533.003,74.552 532.056,74.521 528.898,74.378 C525.979,74.244 524.393,73.757 523.338,73.347 C521.94,72.803 520.942,72.155 519.894,71.106 C518.846,70.057 518.197,69.06 517.654,67.663 C517.244,66.606 516.755,65.022 516.623,62.101 C516.479,58.943 516.448,57.996 516.448,50 C516.448,42.003 516.479,41.056 516.623,37.899 C516.755,34.978 517.244,33.391 517.654,32.338 C518.197,30.938 518.846,29.942 519.894,28.894 C520.942,27.846 521.94,27.196 523.338,26.654 C524.393,26.244 525.979,25.756 528.898,25.623 C532.057,25.479 533.004,25.448 541,25.448 C548.997,25.448 549.943,25.479 553.102,25.623 C556.021,25.756 557.607,26.244 558.662,26.654 C560.06,27.196 561.058,27.846 562.106,28.894 C563.154,29.942 563.803,30.938 564.346,32.338 C564.756,33.391 565.244,34.978 565.378,37.899 C565.522,41.056 565.552,42.003 565.552,50 C565.552,57.996 565.522,58.943 565.378,62.101 M570.82,37.631 C570.674,34.438 570.167,32.258 569.425,30.349 C568.659,28.377 567.633,26.702 565.965,25.035 C564.297,23.368 562.623,22.342 560.652,21.575 C558.743,20.834 556.562,20.326 553.369,20.18 C550.169,20.033 549.148,20 541,20 C532.853,20 531.831,20.033 528.631,20.18 C525.438,20.326 523.257,20.834 521.349,21.575 C519.376,22.342 517.703,23.368 516.035,25.035 C514.368,26.702 513.342,28.377 512.574,30.349 C511.834,32.258 511.326,34.438 511.181,37.631 C511.035,40.831 511,41.851 511,50 C511,58.147 511.035,59.17 511.181,62.369 C511.326,65.562 511.834,67.743 512.574,69.651 C513.342,71.625 514.368,73.296 516.035,74.965 C517.703,76.634 519.376,77.658 521.349,78.425 C523.257,79.167 525.438,79.673 528.631,79.82 C531.831,79.965 532.853,80.001 541,80.001 C549.148,80.001 550.169,79.965 553.369,79.82 C556.562,79.673 558.743,79.167 560.652,78.425 C562.623,77.658 564.297,76.634 565.965,74.965 C567.633,73.296 568.659,71.625 569.425,69.651 C570.167,67.743 570.674,65.562 570.82,62.369 C570.966,59.17 571,58.147 571,50 C571,41.851 570.966,40.831 570.82,37.631"></path>';
        $html[] = '</g>';
        $html[] = '</g>';
        $html[] = '</g>';
        $html[] = '</svg>';
        $html[] = '</div>';
        $html[] = '<div style="padding-top: 8px;">';
        $html[] = '<div style=" color:#3897f0; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:550; line-height:18px;">Voir cette publication sur Instagram</div>';
        $html[] = '</div>';
        $html[] = '<div style="padding: 12.5% 0;"></div>';
        $html[] = '<div style="display: flex; flex-direction: row; margin-bottom: 14px; align-items: center;">';
        $html[] = '<div>';
        $html[] = '<div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(0px) translateY(7px);"></div>';
        $html[] = '<div style="background-color: #F4F4F4; height: 12.5px; transform: rotate(-45deg) translateX(3px) translateY(1px); width: 12.5px; flex-grow: 0; margin-right: 14px; margin-left: 2px;"></div>';
        $html[] = '<div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(9px) translateY(-18px);"></div>';
        $html[] = '</div>';
        $html[] = '<div style="margin-left: 8px;">';
        $html[] = '<div style=" background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 20px; width: 20px;"></div>';
        $html[] = '<div style=" width: 0; height: 0; border-top: 2px solid transparent; border-left: 6px solid #f4f4f4; border-bottom: 2px solid transparent; transform: translateX(16px) translateY(-4px) rotate(30deg)"></div>';
        $html[] = '</div>';
        $html[] = '<div style="margin-left: auto;">';
        $html[] = '<div style=" width: 0px; border-top: 8px solid #F4F4F4; border-right: 8px solid transparent; transform: translateY(16px);"></div>';
        $html[] = '<div style=" background-color: #F4F4F4; flex-grow: 0; height: 12px; width: 16px; transform: translateY(-4px);"></div>';
        $html[] = '<div style=" width: 0; height: 0; border-top: 8px solid #F4F4F4; border-left: 8px solid transparent; transform: translateY(-4px) translateX(8px);"></div>';
        $html[] = '</div>';
        $html[] = '</div>';
        $html[] = '<div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center; margin-bottom: 24px;">';
        $html[] = '<div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 224px;"></div>';
        $html[] = '<div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 144px;"></div>';
        $html[] = '</div>';
        $html[] = '</a>';
        $html[] = '</div>';
        $html[] = '</blockquote>';
        $html[] = '<script async src="//www.instagram.com/embed.js"></script>';

        return [
            'blockName' => 'core/html',
            'attrs'     => [],
            'innerHTML' => implode("\n", $html),
        ];
    }

    private function otocustomhtml(DOMElement $element)
    {
        // get data
        $data = $element->getAttribute("data");

        $data = base64_decode($data);
        $data = json_decode($data, true);
        if (empty($data)) {
            return;
        }

        // html
        $html = Arr::get($data, "html", "");
        if (empty($html)) {
            return;
        }

        // create the gutenberg core/html block
        $block = [
            'blockName' => 'core/html',
            'attrs'     => [],
            'innerHTML' => $html,
        ];

        return $block;
    }

    private function otofacebook(DOMElement $element)
    {
        // get href
        $href = $element->getAttribute("href");
        if (empty($href)) {
            return;
        }

        // Create the html markup
        $html = [];
        $html[] = '<div style="display: block;">';
        $html[] = '<div id="fb-root"></div>';
        $html[] = '<script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2"></script>';
        $html[] = '<div class="fb-post" data-href="' . esc_url($href) . '" data-width="500" data-show-text="true"></div>';
        $html[] = '</div>';

        return [
            'blockName' => 'core/html',
            'attrs'     => [],
            'innerHTML' => implode("\n", $html),
        ];
    }

    private function ototiktok(DOMElement $element)
    {
        // get href
        $href = $element->getAttribute("href");
        if (empty($href)) {
            return;
        }

        // Create the tiktok markup
        $tiktokTag = sprintf(
            "<figure class=\"wp-block-embed is-type-video is-provider-tiktok wp-block-embed-tiktok\"><div class=\"wp-block-embed__wrapper\">\n%1\$s\n</div></figure>",
            esc_url($href)
        );

        return [
            'blockName' => 'core-embed/tiktok',
            'attrs'     => [
                'url' => $href,
                'type' => 'video',
                'providerNameSlug' => 'tiktok',
                'responsive' => true,
            ],
            'innerHTML' => $tiktokTag,
        ];
    }

    private function ototwitter(DOMElement $element)
    {
        // get href
        $href = $element->getAttribute("href");
        if (empty($href)) {
            return;
        }

        // Create the video markup
        $twitterTag = sprintf(
            "<figure class=\"wp-block-embed is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n%1\$s\n</div></figure>",
            esc_url($href)
        );

        return [
            'blockName' => 'core-embed/twitter',
            'attrs'     => [
                'url' => $href,
                'type' => 'rich',
                'providerNameSlug' => 'twitter',
                'responsive' => true,
            ],
            'innerHTML' => $twitterTag,
        ];
    }

    /**
     * Get HTML content
     *
     * @param DOMElement $element dom element
     * @return string
     */
    protected function get_html($element)
    {
        // if (! is_a($element, '\DOMElement')) {
        //     return $element;
        // }

        $inner_html = $element->textContent;
        if (0 < $element->childNodes->count()) {
            $inner_html = $element->ownerDocument->saveHTML($this->clean_attributes($element));
        }

        return $inner_html;
    }

    /**
     * Downloads an image from the URL and imports to Media Library.
     *
     * @param string $img_src Image URL.
     * @return array|WP_Error
     */
    private function upload_image($img_src)
    {
        // Attempt to download the image
        $tmp = download_url($img_src);
        if (is_wp_error($tmp)) {
            // If the file were still downloaded make sure its deleted.
            if (file_exists($tmp)) {
                unlink($tmp); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink
            }
            return $tmp;
        }

        // Prepare the file data for sideloading
        $json = [
            'name'     => basename($img_src),
            'type'     => mime_content_type($tmp),
            'tmp_name' => $tmp,
            'size'     => filesize($tmp),
        ];

        // Upload the image
        $attachment_id = media_handle_sideload($json);

        // Delete the temp file if still exists
        if (file_exists($tmp)) {
            unlink($tmp); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_unlink
        }

        // Return error if attachment upload
        if (is_wp_error($attachment_id)) {
            return $attachment_id;
        }

        $img          = [];
        $img['ID']    = absint($attachment_id);
        $img['url']   = wp_get_attachment_url($attachment_id);
        $img['sizes'] = wp_get_attachment_metadata($attachment_id);

        return $img;
    }

    /**
     * Get image alt text
     *
     * @param DOMElement $element dom element
     * @param int        $id attachment id
     * @return string
     */
    private function get_image_alt($element, int $id = 0)
    {
        // First try to get alt attribute from DOM node.
        $img_alt = $element->getAttribute('alt');

        // If alt attribute is empty, try to get it from the attachment post meta (if post ID is available)
        if (empty($img_alt) && 0 < intval($id)) {
            $img_alt = get_post_meta($id, '_wp_attachment_image_alt', true) ?? '';
        }

        return $img_alt;
    }

    /**
     * Validate callback
     *
     * @param array/function/string $callback callback
     * @return bool
     */
    private function is_callback($callback)
    {
        if (is_callable($callback)) {
            return true;
        }

        if (is_callable([__CLASS__, $callback])) {
            return true;
        }

        return false;
    }

    /**
     * Converts a block to Gutenberg Comment Markup.
     *
     * Props: https://github.com/WordPress/gutenberg/blob/05b9e95a63ff1b278f9d6cfb1d63a84b54d1cbda/lib/class-experimental-wp-widget-blocks-manager.php#L265
     *
     * Block Params:
     * - blockName - Name of Gutenberg Block
     * - attrs     - Optional attributes of the Block
     * - innerHTML - Optional body of the Block
     *
     * @param array $block Block data to convert
     * @return string
     */
    public function serialize_block($block)
    {
        if (! isset($block['blockName'])) {
            return false;
        }
        $name = $block['blockName'];
        if (0 === strpos($name, 'core/')) {
            $name = substr($name, strlen('core/'));
        }
        if (empty($block['attrs'])) {
            $opening_tag_suffix = '';
        } else {
            $opening_tag_suffix = ' ' . wp_json_encode($block['attrs']);
        }
        if (empty($block['innerHTML'])) {
            return sprintf(
                '<!-- wp:%s%s /-->',
                $name,
                $opening_tag_suffix
            );
        } else {
            return sprintf(
                '<!-- wp:%1$s%2$s -->%3$s<!-- /wp:%1$s -->',
                $name,
                $opening_tag_suffix,
                $block['innerHTML']
            );
        }
    }
}
