<?php

if( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}


/**
 * Generate Dynamic Styles
 */

function ntvb_generate_dynamic_styles( $content, $block ) {

    // check the block name start with ntvb/
   if ( isset( $block['blockName'] ) && str_contains( $block['blockName'], 'ntvb/' ) ) {

        // take style from blockStyle attrs
        $blockStyle = $block['attrs']['blockStyle'] ?? '';
        if ( $blockStyle ) {
            // create internal style within head tag
            ntvb_enqueue_dynamic_styles( $blockStyle );
        }
    }

    return $content;

}

add_filter( 'render_block', 'ntvb_generate_dynamic_styles', 10, 2 );


// Enqueue Dynamic Styles
function ntvb_enqueue_dynamic_styles( $styles ) {
    if ( ! empty( $styles ) && is_string( $styles ) ) {
        $handle = 'ntvb-block-' . wp_rand( 100, 10000 );
        wp_register_style( $handle, false, array(), NTVB_VERSION, 'all' );
        wp_enqueue_style( $handle, false, array(), NTVB_VERSION, 'all' );
        wp_add_inline_style( esc_html( $handle ), esc_html( $styles ) );
    }
}