<?php

/**
 * Featured Museum Posts Block Template.
 *
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during AJAX preview.
 * @param   (int|string) $post_id The post ID this block is saved to.
 */

// Create id attribute allowing for custom "anchor" value.
$id = 'featured-museum-posts-' . $block['id'];
if( !empty($block['anchor']) ) {
    $id = $block['anchor'];
}

// Create class attribute allowing for custom "className" and "align" values.
$className = 'featured-museum-posts';
if( !empty($block['className']) ) {
    $className .= ' ' . $block['className'];
}

?>

<section id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">

    <?php 
        if ( get_field( 'show_heading' )[0] == 'yes' ) {
            echo '<h2>' . get_field( 'section_heading' ) . '</h2>';
        }
    ?>

    <?php 

        $news = get_field( 'select_museum_posts' );
        $news_ids = [];

        foreach ($news as $item ) {
            $news_ids[] = $item->ID;
        }

        $news_blocks = new WP_Query(
            array(
                'post_type' => 'museum',
                'post__in'  => $news_ids,
                'orderby'   => 'post__in',
                'order'     => 'ASC',
            )
        );

        if ( $news_blocks->have_posts() ) {
            echo '<div class="news-wrapper ' . ( is_front_page() ? '' : 'mb-nor' ) . '">';
                while ( $news_blocks->have_posts() ) {
                    $news_blocks->the_post(); ?>
                    <div class="news">
                        <div class="news-meta">
                            <h3><?php the_title(); ?></h3>
                            <a href="<?php the_permalink(); ?>" class="cta"><?php echo __( 'Lasi vairāk', 'mpwpbk' ); ?></a>
                        </div>
                        <div class="news-image">
                            <a href="<?php the_permalink(); ?>">
                                <img src="<?php echo get_thumb_url( get_the_ID(), 'medium_large' ); ?>" style="background-image: url('<?php echo get_thumb_url( get_the_ID(), 'thumbnail' ) ?>');" width="534" height="352" class="img-fluid" alt="">
                            </a>
                        </div>
                    </div>
                <?php }
                wp_reset_postdata();
            echo '</div>';

            if ( ! is_front_page() ) {
                echo '<a href="' . get_post_type_archive_link( 'museum' ) . '" class="cta">' . __( 'Visi muzeja jaunumi', 'mpwpbk') . '</a>';
            }
            
        }

    ?>
    
</section>

<?php printf( "<script>window.dispatchEvent( new Event('acf/loaded/featured-museum-posts'));</script>" );