<?php
namespace hakoniwa\blocks\filter\slider;

use hakoniwa\blocks\init\Define;
use hakoniwa\blocks\util\Misc;

/**
 * ブロックフィルター
 */
class REGISTER_BLOCK_FILTER {

    /**
     * constructor.
     */
    public function __construct() {
        add_filter( 'render_block_' . Define::value( 'plugin_name' ) . '/slider', array( $this, 'render_block' ), 10, 2 );
    }

    public function render_block( $block_content, $block ) {
        $should_load_enqueue_swiper = ! wp_script_is( Define::value( 'plugin_name' ) . '-swiper' );
        if ( $should_load_enqueue_swiper ) {
            Misc::enqueue_swiper();
        }

        $should_load_view_script = ! wp_script_is( Define::value( 'plugin_name' ) . '-slider-view-script' );

        if ( $should_load_view_script ) {
            wp_enqueue_script(
                Define::value( 'plugin_name' ) . '-slider-view-script'
            );
        }

        $custom_style = '';

        if( array_key_exists( 'paginationColor', $block['attrs'] ) ){
            $paginationcolor = $block['attrs']['paginationColor'];

            $custom_style .= 'background:' . $paginationcolor . ';';
        }
        
        if ( ! empty( $custom_style ) ) {
            $blockid = $block['attrs']['blockID'];
            $style = '.block-' . esc_html( $blockid ) . ' .swiper-pagination:not(.swiper-pagination-fraction) span{';
            $style .= esc_html( $custom_style );
            $style .= '}';

            wp_add_inline_style( Define::value( 'plugin_name' ) . '-slider-style', $style );
        }

        return $block_content;
    }
}

use hakoniwa\blocks\filter\slider;
new REGISTER_BLOCK_FILTER();
