<?php
/**
 * Enqueue the Cover block extension script from the theme.
 */
function mytheme_enqueue_loadmore_extension_editor_script() {
    wp_enqueue_script(
        'pagination-load-more-extension',
        get_stylesheet_directory_uri() . '/extensions/pagination-load-more-extension/pagination-load-more-extension.js',
        array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-hooks', 'wp-compose' ),
        filemtime( get_stylesheet_directory() . '/extensions/pagination-load-more-extension/pagination-load-more-extension.js' ),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'mytheme_enqueue_loadmore_extension_editor_script' );


function my_load_more_scripts() {
    // Enqueue your AJAX load more script (make sure the path is correct)
    wp_enqueue_script( 'pagination-load-more', get_template_directory_uri() . '/extensions/pagination-load-more-extension/pagination-load-more-script.js', array( 'jquery'  ), '1.0', true );

    // Localize the script with the AJAX URL.
    wp_localize_script( 'my-load-more', 'my_load_more_params', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ) );
}
add_action( 'wp_enqueue_scripts', 'my_load_more_scripts' );

/**
 * Filter the output of the Cover block on the frontend.
 *
 * When the "Link to Post" toggle is enabled (linkToPost is true),
 * this function wraps the cover image element (with class "wp-block-cover__background")
 * in an anchor linking to the current post.
 */
function mytheme_loadmore_extension_render( $block_content, $block ) {
	// Check if the block has a 'layout' attribute set to 'load-more'

	if ( isset( $block['attrs']['className'] ) && 'is-load-more' === $block['attrs']['className'] ) {

          global $wp_query;

    // Ensure that the global query is set and supports pagination.
    if ( ! isset( $wp_query->max_num_pages ) || $wp_query->max_num_pages <= 1 ) {
        return '';
    }

    // Get the current page; default to 1 if not set.
    $current_page = max( 1, intval( get_query_var( 'paged' ) ) );

    // If we're already on the last page, do not render the button.
    if ( $current_page >= $wp_query->max_num_pages ) {
        return '';
    }

    // Determine the next page number and build its URL.
    $next_page = $current_page + 1;
    $next_link = get_pagenum_link( $next_page );
    if ( ! $next_link ) {
        return '';
    }

    // Allow for custom button text via block attributes; default to 'Next'.
    $button_text = ( isset( $attributes['text'] ) && ! empty( $attributes['text'] ) )
        ? $attributes['text']
        : __( 'LOAD MORE', 'default' );

    // Construct the HTML output.
    $html  = '<div class="wp-block-query-pagination-next">';
    $html .= sprintf(
        '<a class="wp-block-query-pagination-next__button is-load-more" href="%s">%s</a>',
        esc_url( $next_link ),
        esc_html( $button_text )
    );
    $html .= '</div>';

    return $html;


//		// Optionally, set dynamic values here.
//		// You might pull these from block attributes or your theme options.
//		$current_page = isset( $block['attrs']['page'] ) ? intval( $block['attrs']['page'] ) : 1;
//		$max_pages    = isset( $block['attrs']['maxPages'] ) ? intval( $block['attrs']['maxPages'] ) : 5;
//		$base_url     = isset( $block['attrs']['baseUrl'] ) ? esc_url( $block['attrs']['baseUrl'] ) : home_url( '?query-0-page='.$current_page + 1 );
//   $current_page = isset( $_POST['paged'] ) ? intval( $_POST['paged'] ) : 1;
//        $query_id = $block['attrs']['queryId'];
//		// Build the markup for the Load More button.
//        var_dump( esc_attr($base_url));
//		$block_content = sprintf(
//			'<div class="wp-block-query-pagination" data-layout="load-more" data-page="%d" data-max-pages="%d" data-base-url="%s">
//				<a data-wp-key="query-pagination-next" data-wp-on--click="core/query::actions.navigate" data-wp-on-async--mouseenter="core/query::actions.prefetch" data-wp-watch="core/query::callbacks.prefetch" href="https://stepfoxthemes.com/examiner-2/category/gaming/page/3/" class="wp-block-query-pagination-next" id="block_dd907f"> option 1</a>
//
//				<a href="https://stepfoxthemes.com/examiner-2/category/gaming/page/3/"
//   class="wp-block-query-pagination-next load-more">
//  option 2
//</a>
//
//<a
//  href="'.$base_url.'"
//  class="is-load-more"
//>
//  option 3
//</a>
//' .
//            '
//			</div>',
//			$current_page,
//			$max_pages,
//			$query_id
//		);
	}
	return $block_content;
}
add_filter( 'render_block_core/query-pagination-next', 'mytheme_loadmore_extension_render', 10, 2 );

add_filter( 'blocks.registerBlockType', 'mytheme_extend_query_block', 10, 2 );
function mytheme_extend_query_block( $settings, $name ) {
    if ( 'core/query' === $name ) {
        $settings['attributes']['queryId'] = array(
            'type'    => 'number',
            'default' => 0,
        );
    }
    return $settings;
}



function my_register_load_more_variation() {
    // Make sure the core block is registered.
    if ( ! function_exists( 'register_block_type' ) ) {
        return;
    }

    // Register the block variation for the query pagination next block.
//    register_block_variation(
//        'core/query-pagination-next',
//        array(
//            'name'        => 'load-more',
//            'title'       => __( 'Load More', 'text-domain' ),
//            'description' => __( 'Doubles the list items when clicked instead of replacing them.', 'text-domain' ),
//            'icon'        => 'plus', // Use an appropriate Dashicon or SVG.
//            'attributes'  => array(
//                // This custom attribute lets your front‐end code know it should append posts.
//                '__experimentalLoadMore' => true,
//            ),
//            // Optionally, restrict the variation to a specific scope.
//            'scope'       => array( 'query-pagination' ),
//        )
//    );
}
add_action( 'init', 'my_register_load_more_variation' );