<?php

if (! defined('ABSPATH')) {
    exit;
} final class PufferGo_Tailwind_Block
{
    public const BLOCK_NAME = 'puffergo/tailwind-container';

    public static function serialize(string $html, string $css, string $scope_id, array $config = array()): string
    {
        $html = (string) mb_convert_encoding($html, 'UTF-8', 'UTF-8');
        $css = (string) mb_convert_encoding($css, 'UTF-8', 'UTF-8');
        $scope_id = (string) mb_convert_encoding($scope_id, 'UTF-8', 'UTF-8');
        $attributes = array('content' => $html, 'customCss' => $css, 'scopeId' => $scope_id, );
        $attributes = array_merge($attributes, self::config_attributes($config));

        if (isset($config['blockStyle']) && is_array($config['blockStyle']) && ! empty($config['blockStyle'])) {
            $attributes['blockStyle'] = $config['blockStyle'];
        } $attributes_json = wp_json_encode($attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        if (false === $attributes_json) {
            if (function_exists('puffergo_log')) {
                puffergo_log('[PufferGo] Tailwind block encode failed: ' . json_last_error_msg());
            } $attributes_json = '{}';
        }

return '<!-- wp:' . self::BLOCK_NAME . ' ' . $attributes_json . ' -->' . '<div class="wp-block-puffergo-tailwind-container ' . esc_attr($scope_id) . '">' . $html . '</div>' . '<!-- /wp:' . self::BLOCK_NAME . ' -->';
    }

    private static function config_attributes(array $config): array
    {
        $template = isset($config['configTemplate']) ? (string) $config['configTemplate'] : '';
        $data = isset($config['configData']) ? $config['configData'] : null;

        if ('' === trim($template) || ! is_array($data)) {
            return array();
        } $attributes = array('configTemplate' => (string) mb_convert_encoding($template, 'UTF-8', 'UTF-8'), 'configData' => $data, );

        if (isset($config['configSchema']) && is_array($config['configSchema'])) {
            $attributes['configSchema'] = $config['configSchema'];
        }

if (isset($config['editing']) && is_array($config['editing'])) {
            $attributes['editing'] = $config['editing'];
        }

return $attributes;
    }

    public static function is_tailwind_block(array $block): bool
    {
        return isset($block['blockName']) && self::BLOCK_NAME === $block['blockName'];
    }
}
