<?php

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

/**
 * Blocks Loader Class
 */
class BWDCV_BLOCKS_LOADER {

    /**
     * Constructor
     */
    public function __construct() {

        // Register Blocks
        add_action( 'init', [$this, 'register_blocks'] );

        //Register Block Category
        if ( version_compare( BWDCV_WP_VERSION, '5.8', '>=' ) ) {
            add_filter( 'block_categories_all', [$this, 'register_cv_builder_block_category'], 99999, 2 );
        } else {
            add_filter( 'block_categories', [$this, 'register_cv_builder_block_category'], 99999, 2 );
        }

        // Enqueue Inline style on render block
        add_filter( 'render_block', [$this, 'generate_inline_style_on_render_block'], 10, 2 );

        // enqueue editor assets
        add_action( 'enqueue_block_editor_assets', [$this, 'enqueue_editor_assets'] );

        // enqueue assets for frontend
        add_action( 'enqueue_block_assets', [$this, 'bwdcv_enqueue_assets'], 20 );

        add_action( 'wp_ajax_bwdcv_upload_template_screenshot', [$this, 'handle_template_screenshot_upload'] );

        add_filter( 'post_row_actions', [$this, 'add_view_template_action'], 10, 2 );
        add_action( 'admin_footer', [$this, 'add_template_popup_container'] );
        add_action( 'wp_ajax_bwdcv_get_template_content', [$this, 'bwdcv_get_template_content_for_popup'] );
        add_action( 'admin_enqueue_scripts', [$this, 'enqueue_view_template_popup_scripts'] );

        add_action( 'wp_enqueue_scripts', [$this, 'bwdcv_google_fonts'] );

        if ( !empty( get_option( 'cv_openai_api_key_text', '' ) ) ) {
            add_action( 'wp_ajax_bwdcv_scgp_openai_api_request', [$this, 'bwdcv_scgp_openai_api_handle_request'] );
        }
    }

    private function get_template_image( $post_id ) {
        $screenshot_id = get_post_meta( $post_id, '_template_screenshot_id', true );
        if ( $screenshot_id ) {
            $image_url = wp_get_attachment_image_url( $screenshot_id, 'full' );
            if ( $image_url ) {
                return $image_url;
            }
        }
        $content = get_post_field( 'post_content', $post_id );
        $blocks = parse_blocks( $content );
        foreach ( $blocks as $block ) {
            if ( $block['blockName'] === 'bwdcv/wp-cv-builder-sass' ) {
                if ( isset( $block['attrs']['images'] ) ) {
                    $images = $block['attrs']['images'];

                    // Find image with matching post ID
                    foreach ( $images as $img ) {
                        if ( isset( $img['value'] ) && $img['value'] == $post_id && !empty( $img['imageUrl'] ) ) {
                            return $img['imageUrl'];
                        }
                    }
                }
            }
        }

        return '';
    }
    function enqueue_view_template_popup_scripts() {
        $screen = get_current_screen();
        if ( $screen->base === 'edit' && $screen->post_type === 'cv-templates' ) {
            wp_enqueue_script(
                'view-template-popup',
                plugin_dir_url( __FILE__ ) . 'assets/js/view-template-popup.js',
                array( 'jquery' ),
                '1.0.0',
                true
            );
            wp_enqueue_style(
                'view-template-popup-styles',
                plugin_dir_url( __FILE__ ) . 'assets/css/view-template-popup.css',
                array(),
                '1.0.0'
            );
        }
    }
    public function bwdcv_get_template_content_for_popup() {
        if ( !isset( $_POST['template_id'] ) || !current_user_can( 'edit_posts' ) ) {
            wp_send_json_error( 'Invalid request or insufficient permissions' );
        }

        $template_id = intval( $_POST['template_id'] );
        $template = get_post( $template_id );

        if ( !$template || $template->post_type !== 'cv-templates' ) {
            wp_send_json_error( 'Template not found' );
        }
        $image_url = $this->get_template_image( $template_id );

        $content = '';
        if ( $image_url ) {
            $content = '<div class="template-preview-image"><img src="' . esc_url( $image_url ) . '" style="max-width: 100%; height: auto;" /></div>';
        } else {
            $content = '<div class="no-image-message">No template preview image available.</div>';
        }

        wp_send_json_success( array(
            'content' => $content,
        ) );
    }
    function add_template_popup_container() {
        $screen = get_current_screen();

        if ( $screen->base === 'edit' && $screen->post_type === 'cv-templates' ) {
            ?>
            <div id="template-popup-overlay" style="display: none;">
                <div id="template-popup-container">
                    <div id="template-popup-header">
                        <h2 id="template-popup-title"></h2>
                        <button id="template-popup-close" type="button">×</button>
                    </div>
                    <div id="template-popup-content"></div>
                </div>
            </div>
            <?php
}
    }
    function add_view_template_action( $actions, $post ) {
        // Check if this is our custom post type
        if ( $post->post_type === 'cv-templates' ) {
            $post_id = $post->ID;
            $screenshot_id = get_post_meta( $post_id, '_template_screenshot_id', true );
            $image_url = "";
            if ( $screenshot_id ) {
                $image_url = wp_get_attachment_image_url( $screenshot_id, 'full' );
            }
            // Create the View Template link with data attributes for the popup
            $view_action = sprintf(
                '<a href="#" class="view-template-popup" data-template-id="%d" data-image-url="%s" aria-label="%s">%s</a>',
                $post->ID,
                $image_url,
                esc_attr( sprintf( __( 'View "%s"', 'cv-builder' ), $post->post_title ) ),
                esc_html__( 'View Template', 'cv-builder' )
            );

            // Add our custom action as the last item
            $actions['view_template'] = $view_action;
        }

        return $actions;
    }
    public function handle_template_screenshot_upload() {
        check_ajax_referer( 'template_screenshot_nonce', 'security' );
        if ( !current_user_can( 'administrator' ) ) {
            wp_send_json_error( 'This feature is only available for administrators', 403 );
            return;
        }
        $template_id = isset( $_POST['template_id'] ) ? intval( $_POST['template_id'] ) : 0;
        if ( !empty( $_FILES['file'] ) ) {
            require_once ABSPATH . 'wp-admin/includes/image.php';
            require_once ABSPATH . 'wp-admin/includes/file.php';
            require_once ABSPATH . 'wp-admin/includes/media.php';
            $prev_attachment_id = get_post_meta( $template_id, '_template_screenshot_id', true );
            if ( $prev_attachment_id ) {
                wp_delete_attachment( $prev_attachment_id, true );
            }
            $attachment_id = media_handle_upload( 'file', 0 );
            if ( is_wp_error( $attachment_id ) ) {
                wp_send_json_error( $attachment_id->get_error_message() );
            }
            update_post_meta( $template_id, '_template_screenshot_id', $attachment_id );
            $image_url = wp_get_attachment_url( $attachment_id );
            wp_send_json_success( [
                'url' => $image_url,
                'id'  => $attachment_id,
            ] );
        } else {
            wp_send_json_error( 'No file uploaded' );
        }
    }

    public function bwdcv_scgp_openai_api_handle_request() {
        if ( !isset( $_POST['prompt'] ) ) {
            echo wp_json_encode( ['error' => 'No prompt provided'] );
            wp_die();
        }

        $prompt = sanitize_text_field( $_POST['prompt'] );

        $apiKey = get_option( 'cv_openai_api_key_text', '' );

        $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array(
            'body'    => wp_json_encode( array(
                'model'      => 'gpt-3.5-turbo',
                'messages'   => array(
                    array( 'role' => 'user', 'content' => $prompt ),
                ),
                'max_tokens' => 100,
            ) ),
            'headers' => array(
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $apiKey,
            ),
        ) );

        if ( is_wp_error( $response ) ) {
            echo wp_json_encode( ['error' => $response->get_error_message()] );
        } else {
            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body, true );
            if ( isset( $data['choices'] ) && count( $data['choices'] ) > 0 ) {
                echo wp_json_encode( ['response' => $data['choices'][0]['message']['content']] );
            } else {
                echo wp_json_encode( ['error' => 'No response from AI'] );
            }
        }

        wp_die();
    }
    public function bwdcv_google_fonts() {
        if ( !has_blocks() ) {
            return;
        }

        $blocks = parse_blocks( get_post()->post_content );
        $fonts_to_load = [];
        foreach ( $blocks as $block ) {
            if ( !empty( $block['attrs'] ) && isset( $block['attrs']['typography']['fontFamily'] ) ) {
                $font_family = $block['attrs']['typography']['fontFamily'];

                if ( $font_family && $font_family !== 'inherit' && !in_array( $font_family, $fonts_to_load ) ) {
                    $fonts_to_load[] = $font_family;
                }
            }
        }
        if ( !empty( $fonts_to_load ) ) {
            $font_families = array_map( function ( $font ) {
                return str_replace( ' ', '+', $font ) . ':wght@300;400;500;600;700';
            }, $fonts_to_load );
            $google_fonts_url = 'https://fonts.googleapis.com/css2?family=' .
            implode( '&family=', $font_families ) .
                '&display=swap';
            wp_enqueue_style( 'bwdcv-google-fonts', $google_fonts_url );
        }
    }

    /**
     * Enqueue Editor Assets
     */
    public function enqueue_editor_assets() {
        if ( current_user_can( 'cv_editor' ) ) {
            wp_enqueue_style( 'bwdcv_cv_builder_editor_role', plugin_dir_url( __FILE__ ) . '../assets/admin/css/editor-role.css', array(), BWDCV_VERSION, 'all' );
        }
        $asset_file = plugin_dir_path( __FILE__ ) . '../build/blocks/wp-cv-builder/index.asset.php';
        $script_data = file_exists( $asset_file ) ? include $asset_file : [];
        wp_enqueue_script(
            'bwdcv-custom-block-script',
            plugin_dir_url( __FILE__ ) . '../build/blocks/wp-cv-builder/index.js',
            $script_data['dependencies'],
            $script_data['version'],
            true
        );

        $all_images       = [];
        $cv_template_data = [];

        /*
         * cv-templates post type er sob published template load kora hocche.
         * Admin dashboard theke new template create kore publish/update korle
         * ei query te automatically show hobe.
         */
        $cv_templates = get_posts( [
            'post_type'   => 'cv-templates',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby'     => 'ID',
            'order'       => 'ASC',
        ] );

        foreach ( $cv_templates as $cv_post ) {
            // cvTemplates array te template er full content pathano hocche
            // jate user template select korle block content replace kora jay
            $cv_template_data[] = [
                'id'      => $cv_post->ID,
                'title'   => $cv_post->post_title,
                'content' => $cv_post->post_content,
            ];

            $template_images = [];

            /*
             * PRIMARY: _template_screenshot_id post meta theke screenshot URL newa.
             * Admin save/update korle JS theke AJAX call e ei meta update hoy.
             * Tai ei source e always fresh screenshot URL paowa jay.
             */
            $screenshot_meta_id = get_post_meta( $cv_post->ID, '_template_screenshot_id', true );
            if ( $screenshot_meta_id ) {
                $screenshot_url = wp_get_attachment_url( $screenshot_meta_id );
                if ( $screenshot_url ) {
                    $template_images[] = [
                        'imageUrl' => $screenshot_url,
                        'label'    => $cv_post->post_title,
                        'value'    => (string) $cv_post->ID,
                    ];
                }
            }

            /*
             * FALLBACK: Block attrs er "images" array theke screenshot URL newa.
             * Screenshot meta save hoar age ba older templates er jonno use hobe.
             */
            if ( empty( $template_images ) ) {
                $blocks = parse_blocks( $cv_post->post_content );
                foreach ( $blocks as $block ) {
                    if (
                        isset( $block['blockName'], $block['attrs']['images'] ) &&
                        $block['blockName'] === 'bwdcv/wp-cv-builder' &&
                        is_array( $block['attrs']['images'] )
                    ) {
                        foreach ( $block['attrs']['images'] as $image ) {
                            if ( isset( $image['imageUrl'] ) ) {
                                $template_images[] = [
                                    'imageUrl' => $image['imageUrl'],
                                    'label'    => isset( $image['label'] ) ? $image['label'] : '',
                                    'value'    => isset( $image['value'] ) ? $image['value'] : '',
                                ];
                            }
                        }
                        break;
                    }
                }
            }

            /*
             * allImages array te isCustom: true flag pathano hocche
             * jate JS side e ImageSelector e normal style1..style28 theke
             * alag filter logic use kora jay custom templates er jonno.
             */
            if ( !empty( $template_images ) ) {
                $all_images[] = [
                    'post_id'    => $cv_post->ID,
                    'post_title' => $cv_post->post_title,
                    'images'     => $template_images,
                    'isCustom'   => true,
                ];
            }
        }

        // Get all subscription products in the 'cv-subscription' category
        $current_user_id = get_current_user_id();
        $subscription_products = get_posts( [
            'post_type'      => 'product',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'tax_query'      => [
                [
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => 'cv-subscription',
                ],
            ],
        ] );
        $product_ids = array_map( fn( $product ) => $product->ID, $subscription_products );
        $has_per_download = false;
        $has_billing_period = false;
        foreach ( $product_ids as $product_id ) {
            if ( get_post_meta( $product_id, '_subscription_per_download', true ) ) {
                $has_per_download = true;
            }
            if ( get_post_meta( $product_id, '_subscription_billing_period', true ) ) {
                $has_billing_period = true;
            }
            if ( $has_per_download && $has_billing_period ) {
                break;
            }
        }
        $subscription_orders = [];
        if ( $has_per_download || $has_billing_period ) {
            $orders = wc_get_orders( [
                'customer' => $current_user_id,
                'limit'    => -1,
                'status'   => ['processing', 'completed'],
            ] );
            foreach ( $orders as $order ) {
                foreach ( $order->get_items() as $item ) {
                    $product_id = $item->get_product_id();

                    if ( in_array( $product_id, $product_ids, true ) ) {
                        $subscription_orders[] = [
                            'order_id'       => $order->get_id(),
                            'status'         => $order->get_status(),
                            'product_id'     => $product_id,
                            'per_download'   => (int) $order->get_meta( '_subscription_per_download', true ),
                            'billing_period' => $order->get_meta( '_subscription_billing_period', true ),
                        ];
                        break;
                    }
                }
            }
        }

        $options = get_option( 'bwd_userfronted_options' );
        $main_options = get_option( 'bwdcv_preview_options', array() );
        $checkboxes = [];
        for ( $i = 1; $i <= 28; $i++ ) {
            $checkbox_value = isset( $main_options[$i] ) ? $main_options[$i] : '';
            $checkboxes[$i] = $checkbox_value ? "1" : "0";
        }

        $styleOptions = [];
        for ( $i = 1; $i <= 28; $i++ ) {
            $option_key = 'cv_allow_style' . $i;
            // $option_value = isset($main_options[$option_key]) ? $main_options[$option_key] : '';
            // $styleOptions[$option_key] = ($option_value === 'on' || $option_value === '1') ? "1" : "0";
            $styleOptions[$option_key] = !empty( $main_options[$option_key] ) ? "1" : "0";
        }
        // $license_status = \BWDCV_BLOCKS_CLASS::instance()->bwdcv_get_license_status();
        $license_status = 'inactive';
        if ( class_exists( 'BWDCV_BLOCKS_CLASS_PRO' ) ) {
            $license_status = BWDCV_BLOCKS_CLASS_PRO::instance()->bwdcv_get_license_status();
        }
        /*
         * Custom template IDs gulo bwdcv_data.checkboxes e active hisebe mark kora hocche.
         * ImageSelector e styleNumber check kore, tai custom template er post_id k
         * checkboxes e '1' set kora dorkar - nahole ImageSelector filter e block kore debe.
         */
        $custom_template_checkboxes = $checkboxes;
        foreach ( $all_images as $custom_tpl ) {
            $custom_template_checkboxes[ $custom_tpl['post_id'] ] = '1';
        }

        wp_localize_script( 'bwdcv-custom-block-script', 'userData', array(
            'siteUrl'            => site_url(),
            'dashboardUrl'       => get_permalink( $options['dashboard_page'] ),
            'pageSlug'           => site_url() . '/cv/' . get_post_field( 'post_name', get_post() ),
            'options'            => $styleOptions,
            'isAdmin'            => current_user_can( 'administrator' ),
            // cv_editor role check: admin build kora template use korte parbe
            'isCvEditor'         => current_user_can( 'cv_editor' ),
            'subscriptionOrders' => $subscription_orders,
            'tokenUrl'           => get_cv_page_token_url(),
            'allImages'          => $all_images,
            'cvTemplates'        => $cv_template_data,
            'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
            'nonce'              => wp_create_nonce( 'template_screenshot_nonce' ),

        ) );

        wp_localize_script( 'bwdcv-custom-block-script', 'bwdcv_data', array(
            // custom template ID gulo checkboxes e active hisebe add kora holo
            'checkboxes'    => $custom_template_checkboxes,
            'options'       => $styleOptions,
            'licenseStatus' => $license_status,

        ) );
        wp_enqueue_script(
            'bwdcv-blocks-global-js',
            BWDCV_ADMIN_URL . './dist/global.js',
            [],
            BWDCV_VERSION,
            true
        );
        wp_enqueue_script( 'bwdcv-scgp-openai-api-script', plugin_dir_url( __FILE__ ) . '../assets/public/js/openai-api-script.js', array( 'jquery' ), null, true );
        wp_localize_script( 'bwdcv-scgp-openai-api-script', 'bwdcv_scgp_openai_api_vars', array(
            'api_url' => admin_url( 'admin-ajax.php' ),
        ) );
    }

    public function bwdcv_enqueue_assets() {
        if ( is_singular( 'cv' ) ) {
            wp_enqueue_style( 'bwdcv_cv_builder_single', plugin_dir_url( __FILE__ ) . '../build/blocks/wp-cv-builder/style-index.css', array(), BWDCV_VERSION, 'all' );
            wp_enqueue_script( 'bwdcv-cv-main-script', plugin_dir_url( __FILE__ ) . '../includes/assets/js/main.js', array(), BWDCV_VERSION, false );
        }
    }

    /**
     * Blocks Category
     */
    public function register_cv_builder_block_category( $categories, $post ) {
        return array_merge(
            [
                [
                    'slug'  => 'bwdcv-cv-builder-blocks',
                    'title' => esc_html__( 'CV Builder Blocks', 'cv-builder' ),
                ],
            ],
            $categories
        );
    }

    /**
     * Load Blocks
     */

    public function register_blocks() {

        // get all blocks from includes/blocks/blocks.php
        require_once BWDCV_DIR_PATH . './includes/blocks/blocks.php';

        // Register Blocks
        if ( !empty( $bwdcv_blocks ) && is_array( $bwdcv_blocks ) ) {
            foreach ( $bwdcv_blocks as $block ) {
                $this->register_single_block( $block );
            }
        }

    }

    /**
     * Register Single Block
     */
    public function register_single_block( $block ) {
        register_block_type(
            BWDCV_DIR_PATH . './build/blocks/' . $block['name'],
            [
                'render_callback' => [$this, 'bwdcv_cv_builder_render_callback'],
            ]
        );

    }

    public function bwdcv_cv_builder_render_callback( $attributes, $content, $block ) {
        $block_name = $block->name;
        if ( $block_name === 'bwdcv/wp-cv-builder' ) {
            $style = isset( $attributes['style'] ) ? $attributes['style'] : 'style1';
            switch ( $style ) {
            case 'style21':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twentyOne-render.php';
                $render_func = 'bwdcv_render_style_twentyOne';
                break;
            case 'style19':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-nineteen-render.php';
                $render_func = 'bwdcv_render_style_nineteen';
                break;
            case 'style1':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-one-render.php';
                $render_func = 'bwdcv_render_style_one';
                break;
            case 'style2':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-two-render.php';
                $render_func = 'bwdcv_render_style_two';
                break;
            case 'style4':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-four-render.php';
                $render_func = 'bwdcv_render_style_four';
                break;
            case 'style5':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-five-render.php';
                $render_func = 'bwdcv_render_style_five';
                break;
            case 'style6':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-six-render.php';
                $render_func = 'bwdcv_render_style_six';
                break;
            case 'style3':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-three-render.php';
                $render_func = 'bwdcv_render_style_three';
                break;
            case 'style7':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-seven-render.php';
                $render_func = 'bwdcv_render_style_seven';
                break;
            case 'style8':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-eight-render.php';
                $render_func = 'bwdcv_render_style_eight';
                break;
            case 'style9':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-nine-render.php';
                $render_func = 'bwdcv_render_style_nine';
                break;
            case 'style10':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-ten-render.php';
                $render_func = 'bwdcv_render_style_ten';
                break;
            case 'style11':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-eleven-render.php';
                $render_func = 'bwdcv_render_style_eleven';
                break;
            case 'style12':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twelve-render.php';
                $render_func = 'bwdcv_render_style_twelve';
                break;
            case 'style13':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-thirteen-render.php';
                $render_func = 'bwdcv_render_style_thirteen';
                break;
            case 'style14':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-fourteens-render.php';
                $render_func = 'bwdcv_render_style_fourteen';
                break;
            case 'style15':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-fifteen-render.php';
                $render_func = 'bwdcv_render_style_fifteen';
                break;
            case 'style16':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-sixteens-render.php';
                $render_func = 'bwdcv_render_style_sixteen';
                break;
            case 'style17':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-seventeen-render.php';
                $render_func = 'bwdcv_render_style_seventeen';
                break;
            case 'style18':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-eighteen-render.php';
                $render_func = 'bwdcv_render_style_eighteen';
                break;
            case 'style20':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twenty-render.php';
                $render_func = 'bwdcv_render_style_twenty';
                break;
            case 'style22':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twentyTwo-render.php';
                $render_func = 'bwdcv_render_style_twentyTwo';
                break;
            case 'style23':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twentyThree-render.php';
                $render_func = 'bwdcv_render_style_twentyThree';
                break;
            case 'style24':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twentyFour-render.php';
                $render_func = 'bwdcv_render_style_twentyFour';
                break;
            case 'style25':
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/templates/style-twentyFive-render.php';
                $render_func = 'bwdcv_render_style_twentyFive';
                break;

            default:
                require_once plugin_dir_path( __FILE__ ) . '../src/blocks/wp-cv-builder/bwdcv-cv-builder-render.php';
                $render_func = 'bwdcv_cv_builder_render_content';
                break;
            }
            if ( function_exists( $render_func ) ) {
                return $render_func( $attributes, $content );
            }
        }
        return '';
    }

    /**
     * Register Inline Style
     */
    function generate_inline_style_on_render_block( $block_content, $block ) {
        if ( isset( $block['blockName'] ) && str_contains( $block['blockName'], 'bwdcv/' ) ) {
            $dom = new DOMDocument();
            @$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $block_content );

            if ( !empty( $block['attrs']['blockStyle'] ) ) {
                $style = $block['attrs']['blockStyle'];
                $style = wp_strip_all_tags( preg_replace( '/\s+/', ' ', $style ) );
                $style = str_replace( 'text-transform: uppercase', 'text-transform: none; font-variant: normal;', $style );

                $style_tag = "<style>{$style}</style>";
                $position = strpos( $block_content, '>' );
                if ( $position !== false ) {
                    $block_content = substr_replace( $block_content, $style_tag, $position + 1, 0 );
                } else {
                    $block_content = $style_tag . $block_content;
                }
            }
        }
        return $block_content;
    }
}

new BWDCV_BLOCKS_LOADER();
