<?php 


/**
 * SCROLL-SEQUENCE SHORTCODE 
 * Use: [scroll-sequence id="post_id"] to display a scroll sequence post. Post ID is required and should be an id of a post of type 'scroll-sequence'.
 * The shortcode will render the first (path) or container block found in the post content.
 * @param array $atts Shortcode attributes.
 * @return string Rendered HTML for the scroll sequence post.
 */
function scroll_sequence_shortcode($atts) {
    $atts = shortcode_atts(['id' => 0], $atts);
    $post_id = intval($atts['id']);
    if (!$post_id) return '<p style="color:red; padding:1rem; border: 1px solid red;">[scroll-sequence] shortcode error: No post ID. Please provide a valid post ID.</p>';
    $post = get_post($post_id);
    if (!$post || $post->post_type !== 'scroll-sequence') return '<p style=style="color:red; padding:1rem; border: 1px solid red;">[scroll-sequence] shortcode error: Invalid post type.</p>';

    $blocks = parse_blocks($post->post_content);
    
    $allowed = [
        'scroll-sequence/v2-path',
        'scroll-sequence/v2-container',
        'scroll-sequence/v2-scene',
        'scroll-sequence/v2-canvas1d',
        'scroll-sequence/v2-canvas2d',
        'scroll-sequence/v2-canvas3d',
    ];

    foreach ($blocks as $block) {
        if ( empty( $block['blockName'] ) ) {
            continue;
        }

        // If this top-level block is one of the allowed types, render and return it
        if ( in_array( $block['blockName'], $allowed, true ) ) {
            return render_block( $block );
        }
    }

    return '<p style=style="color:red; padding:1rem; border: 1px solid red;">[scroll-sequence] shortcode error: No valid blocks found in the root of the content. Please make sure Scrollsequence blocks are on the top level of the post content.</p>';
}
add_shortcode('scroll-sequence', 'scroll_sequence_shortcode');

/**
 * Add Columns to Custom Post Type List
 *
 *
 */
function scroll_sequence_admin_columns( $columns ) {

    $columns = array(
        'cb' => $columns['cb'],
        'title' => __( 'Title', 'scrollsequence' ),
        'scroll_sequence_shortcode' => __( 'Shortcode', 'scrollsequence' ),
        'date' => __( 'Date', 'scrollsequence' ),
        'author' => __( 'Author', 'scrollsequence' ),
    );

    return $columns;
}
add_action( 'manage_scroll-sequence_posts_columns', 'scroll_sequence_admin_columns',5 );

function scroll_sequence_admin_column_content( $column, $id ) {
    if( 'scroll_sequence_shortcode' == $column ) {
        echo '[scroll-sequence id="'.esc_attr((int)$id).'"]';
    }
}
add_action( 'manage_scroll-sequence_posts_custom_column', 'scroll_sequence_admin_column_content',5,2 );
