<?php
add_filter( 'render_block_core/paragraph', 'kingcabs_render_progressbar_block_variation', 10, 2 );
/**
 * Render counter block markup.
 *
 * @since 1.5.2
 *
 * @param string $html  Block html content.
 * @param array  $block Block data.
 *
 * @return string
 */
function kingcabs_render_progressbar_block_variation( string $html, array $block ): string {

    // ensure attrs exist
    if ( empty( $block['attrs'] ) || ! array_key_exists( 'className', $block['attrs'] ) || $block['attrs']['className'] !== 'is-sp-progressbar' ) {
        return $html;
    }

    $dom = dom( $html );
    $p   = get_dom_element( 'p', $dom );

    if ( ! $p ) {
        return $html;
    }

    $defaults = [
        'progressValue'      => '10',
        'progressbarLayout'  => 'line',
        'progressbarStyle'   => 'style1',
        'progressbarTitle'   => 'Progressbar',
        'progressCircleSize' => '20',
        'progressColor'      => '#000000',
        'progressTextColor'  => '#ffffff',
    ];

    // merge but ensure $block['attrs'] is array
    $attrs = array_merge( $defaults, (array) $block['attrs'] );

    /**
     * SANITIZE / NORMALIZE incoming attributes
     * - layout/style: allow only safe class characters
     * - numeric: absint/float
     * - colors: sanitize_hex_color
     * - title: sanitize_text_field
     */
    $layout_raw = (string) $attrs['progressbarLayout'];
    $layout_clean = sanitize_html_class( $layout_raw, $defaults['progressbarLayout'] );

    $style_raw = (string) $attrs['progressbarStyle'];
    $style_clean = sanitize_html_class( $style_raw, $defaults['progressbarStyle'] );

    // numeric / percent
    $progress_value = absint( $attrs['progressValue'] );
    if ( $progress_value < 0 ) { $progress_value = absint( $defaults['progressValue'] ); }

    // circle size -> float (rem)
    $circle_size_raw = floatval( $attrs['progressCircleSize'] );
    if ( $circle_size_raw <= 0 ) {
        $circle_size_raw = floatval( $defaults['progressCircleSize'] );
    }

    // colors
    $progress_color = sanitize_hex_color( $attrs['progressColor'] );
    $progress_text_color = sanitize_hex_color( $attrs['progressTextColor'] );

    if ( empty( $progress_color ) ) {
        $progress_color = $defaults['progressColor'];
    }
    if ( empty( $progress_text_color ) ) {
        $progress_text_color = $defaults['progressTextColor'];
    }

    // title
    $progress_title = sanitize_text_field( $attrs['progressbarTitle'] );

    /**
     * If layout is not line, we build the wrapper HTML (original behaviour)
     * BUT make sure to escape all attributes and values properly.
     */
    if ( $layout_clean !== $defaults['progressbarLayout'] ) {
        // Build HTML with proper escaping for attributes and inline CSS variables
        $html = '<div class="is-sp-progressbar-wrapper layout-' . esc_attr( $layout_clean ) . ' ' . esc_attr( $style_clean ) . '" data-progress="' . esc_attr( $progress_value ) . '"'
            . ' style="--progress-circle-diameter: ' . esc_attr( $circle_size_raw ) . 'rem; --progress-blue: ' . esc_attr( $progress_color ) . '; --progress-text-color: ' . esc_attr( $progress_text_color ) . ';"'
            . '>'
            . '<div class="progress" style="--progress-percent: 0;">'
                . '<div class="bar-overflow"><div class="bar"></div></div>'
                . '<div class="circle"></div>'
                . '<div class="info">'
                    . '<h2 class="number" data-number="' . esc_attr( $progress_value ) . '" data-display="0%"></h2>'
                    . '<p>' . esc_html( $progress_title ) . '</p>'
                    . '<div class="info-arrow"></div>'
                . '</div>'
                . '<div class="min-max"><span>start</span><span>End</span></div>'
            . '</div>'
        . '</div>';

        return $html;
    }

    /**
     * For 'line' layout (original DOM-based modification),
     * set safe attributes on the <p> element using the sanitized values above.
     */
    // ensure we preserve existing classes but sanitize them too
    $existing_classes = (string) $p->getAttribute( 'class' );
    // break and sanitize each class token with sanitize_html_class to avoid injection via class attribute
    $class_tokens = array_filter( array_map( 'trim', explode( ' ', $existing_classes ) ) );
    $sanitized_tokens = [];
    foreach ( $class_tokens as $token ) {
        $sanitized_tokens[] = sanitize_html_class( $token );
    }
    // push a safe extra class (if needed)
    $sanitized_tokens[] = 'is-sp-progressbar-line'; // optional marker class for 'line' layout
    $p->setAttribute( 'class', implode( ' ', array_unique( $sanitized_tokens ) ) );

    // set data attributes using esc_attr-equivalent values (DOMDocument will handle raw values,
    // but we've sanitized/normalized them above)
    $p->setAttribute( 'data-value', (string) $progress_value );
    $p->setAttribute( 'data-layout', (string) $layout_clean );
    $p->setAttribute( 'data-style', (string) $style_clean );
    $p->setAttribute( 'data-title', (string) $progress_title );

    // trim text content
    $p->textContent = trim( $p->textContent );

    // Save DOM and wrap with safe wrapper
    $saved = $dom->saveHTML();

    return "<div class='is-sp-progressbar-wrapper'>" . $saved . "</div>";
}

add_filter( 'kingcabs_block_inline_css', 'kingcabs_add_progressbar_support_css', 10, 2 );
/**
 * Conditionally add progressbar CSS.
 *
 * @since 1.5.2
 *
 * @param string $css   Inline css.
 * @param string $html Block html content.
 *
 * @return string
 */
function kingcabs_add_progressbar_support_css( string $css, string $html ): string {
    /** classic theme compatible */
    if ( ! $html ) {
        global $post;
        if ( $post && $post->post_content ) {
            $html = apply_filters( 'the_content', $post->post_content );
        }
    }

    if ( str_contains( $html, 'is-sp-progressbar' ) ) {
        $dir = dirname( __DIR__, 1 );
        // guard file_get_contents to avoid warnings if file missing
        $css_path = $dir . '/assets/css/progress.css';
        if ( file_exists( $css_path ) ) {
            $css .= file_get_contents( $css_path );
        }
    }

    return $css;
}

add_filter( 'kingcabs_block_inline_js', 'kingcabs_add_progressbar_support_js', 10, 2 );
/**
 * Conditionally add progressbar JS.
 *
 * @param string $js
 * @param string $html
 *
 * @return string
 */
function kingcabs_add_progressbar_support_js( string $js, string $html ): string {
    /** classic theme compatible */
    if ( ! $html ) {
        global $post;
        if ( $post && $post->post_content ) {
            $html = apply_filters( 'the_content', $post->post_content );
        }
    }

    if ( str_contains( $html, 'is-sp-progressbar' ) ) {
        $dir = dirname( __DIR__, 1 );
        $js_path = $dir . '/assets/js/progressbar.js';
        if ( file_exists( $js_path ) ) {
            $js .= file_get_contents( $js_path );
        }
    }

    return $js;
}
