<?php


function bb_render_saved_section_shortcode($atts) {
    $atts = shortcode_atts([
        'id'  => '',
        'key' => '',
    ], $atts, 'bb_saved_section');

    $post_id = 0;

    if (!empty($atts['key'])) {
        $post = get_posts([
            'post_type'  => ['page', 'az_section'],
            'meta_key'   => 'section_key',
            'meta_value' => sanitize_text_field($atts['key']),
            'numberposts'=> 1,
        ]);
        if (!empty($post)) {
            $post_id = $post[0]->ID;
        }
    } elseif (!empty($atts['id'])) {
        $post_id = absint($atts['id']);
    }

    if (!$post_id) {
        return '<!-- bb_saved_section: No valid section -->';
    }

    $is_bb = get_post_meta($post_id, '_fl_builder_enabled', true);
    if ($is_bb !== '1') {
        return '<!-- bb_saved_section: Not a BB layout -->';
    }

    // ✅ Enqueue BB layout styles/scripts manually
    FLBuilder::enqueue_layout_styles_scripts($post_id);

    // Get and render the content
    $content = get_post_field('post_content', $post_id);
    if (!$content) return '<!-- No content -->';

    return '<div class="bb-shortcode-section">' . apply_filters('the_content', $content) . '</div>';

}

// Register the shortcode with WordPress
add_shortcode('bb_saved_section', 'bb_render_saved_section_shortcode');


