<?php
/**
 * Blocks Initializer
 *
 * Enqueue CSS/JS of all the blocks.
 *
 * @since   1.0.0
 * @package xgate
 */

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

/**
 * Enqueue Gutenberg block assets for both frontend + backend.
 *
 * Assets enqueued:
 * 2. blocks.build.js - Backend.
 *
 * @uses {wp-blocks} for block type registration & related functions.
 * @uses {wp-element} for WP Element abstraction — structure of blocks.
 * @uses {wp-i18n} to internationalize the block's text.
 * @uses {wp-editor} for WP editor styles.
 * @since 1.0.0
 */
function xgate_latest_posts_assets()
{ // phpcs:ignore

    // Register block editor script for backend.
    wp_register_script(
        'xgate-latest-posts-js', // Handle.
        get_template_directory_uri() . '/inc/blocks/latest-posts/build/latest-posts.js', // Block.build.js: We register the block here. Built with Webpack.
        array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components'), // Dependencies, defined above.
        null, // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.build.js' ), // Version: filemtime — Gets file modification time.
        true // Enqueue the script in the footer.
    );

    // WP Localized globals. Use dynamic PHP stuff in JavaScript via `cgbGlobal` object.
    wp_localize_script(
        'xgate-latest-posts-js',
        'cgbGlobal', // Array containing dynamic data for a JS Global.
        [
            'pluginDirPath' => plugin_dir_path(__DIR__),
            'pluginDirUrl' => plugin_dir_url(__DIR__),
        ]
    );

    /**
     * Register Gutenberg block on server-side.
     *
     * Register the block on server-side to ensure that the block
     * scripts and styles for both frontend and backend are
     * enqueued when the editor loads.
     *
     * @link https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type#enqueuing-block-scripts
     * @since 1.16.0
     */
    register_block_type(
        'xgate/latest-posts', array(
            'editor_script' => 'xgate-latest-posts-js',
            'render_callback' => 'latest_posts_render'
        )
    );
}

function latest_posts_render( $attributes, $content ) {
    $numberOfPosts = isset( $attributes['numberOfPosts'] ) ? $attributes['numberOfPosts'] : '';
    
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $numberOfPosts,
        'post_status' => 'publish',
    );
    $posts = get_posts($args);

    ob_start(); // Start output buffering

    $output = '';

    if (!empty($posts)) {
        $output .= '    <section class="w-full px-6 lg:px-16 mx-auto max-w-screen-2xl py-10 sm:py-20">
            <div class="flex justify-between items-center">
            <h3>Featured blog posts</h3>
            <a role="button" href="/blog" class="button button-primary blog-posts-button">See All</a>
        </div>
                <div class="grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-16 my-6">';
        foreach ($posts as $index => $post) {
            if($index >= 3) break;
            setup_postdata($post);
            
            $output .= '<a class="blog-post  flex flex-col shadow-xl rounded-xl bg-white" href="'.  get_the_permalink($post) .'">
    <div class="relative min-h-[200px] w-full"><img alt="Blog image 9565" loading="lazy" decoding="async"
            data-nimg="fill" class="bg-gray-200 object-cover  rounded-tl-xl rounded-tr-xl" sizes="100vw"
            src="'. get_the_post_thumbnail_url($post->ID, 'medium_large') .'"
            style="position: absolute; height: 100%; width: 100%; inset: 0px; color: transparent;">
    </div>
    <div class="p-8 w-full ">
        <p class="text-xgate-blue text-sm mb-2">'.  get_the_author() .' •
            '.  get_the_date() .'</p>
        <h2 class="text-2xl mb-2 ">'.  get_the_title($post) .'</h2>
        <div class="text-gray-700 text-base mb-4 ">
            '.  get_the_excerpt($post) .'
        </div>
        <div class="flex gap-2">';
        $categories = get_the_category();
        if ($categories) :
            foreach ($categories as $category) :
            $output .= '<div
class="relative max-w-fit min-w-min inline-flex items-center justify-between box-border whitespace-nowrap px-1 h-7 text-small rounded-full bg-primary text-white">
<span class="flex-1 text-inherit font-normal px-2">'. esc_html($category->name) .'</span>
</div>';
            endforeach;
        endif;
            $output .= '        </div>
                    </div>
                    </a>';

        }
        $output .= '</div>
           <div class="w-full">
            <a role="button" href="/blog" class="button button-primary blog-posts-button blog-posts-button-mobile text-center">See All</a>
        </div>
</section>';
        wp_reset_postdata();
    } else {
            $output .= '<p>No recent posts available.</p>';
    }

wp_reset_postdata(); // Reset post data

return $output; // Return the buffered content
}


// Hook: Block assets.
add_action('init', 'xgate_latest_posts_assets');