<?php
$terms = get_the_terms(get_the_ID(), 'category');
$term_ids = array();

if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $key => $term) {
        $term_ids[] = $term->term_id;
    }
}

$the_query = new \WP_Query([
    'post__not_in' => [get_the_ID()],
    'post_type' => 'post',
    'posts_per_page' => rt_get_option('single_related_count', 6),
    'ignore_sticky_posts' => 1,
    'tax_query' => [
        [
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => $term_ids,
            'operator' => 'IN',
        ],
    ],
]);

// Swiper options
$slider_options = htmlspecialchars(json_encode([
    'slidesPerView' => 1,
    'spaceBetween' => 16,
    'itemWrapper' => '.rt-post__thumbnail',
    'breakpoints' => [
        781 => [
            'slidesPerView' => 3,
            'spaceBetween' => 30,
        ],
    ],
]));
?>


<?php if ($the_query->have_posts() && rt_get_option('single_related', true)) : ?>
    <div class="wp-block-group has-global-padding mt-40 md:mt-60">
        <div class="rt-post-relateds">
            <div class="rt-block-heading">
                <h2 class="rt-block-heading__title"><?php echo __('Related Posts', 'jelajah-text') ?></h2>
            </div>
            <div class="wp-block-group mt:30 md:mt-60">

                <div id="posts-related-carousel" class="rt-swiper is-swiper-pagination-outside">
                    <div class="swiper js-swiper" data-options="<?php echo esc_attr($slider_options) ?>">
                        <div class="swiper-wrapper">
                            <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
                                <div class="swiper-slide">
                                    <div class="rt-swiper-item">
                                        <?php rt_get_template_part('single/related-post') ?>
                                    </div>
                                </div>
                            <?php endwhile ?>

                            <?php wp_reset_postdata(); ?>
                        </div>
                        <div class="swiper-pagination">
                            <span class="swiper-pagination-bullet"></span>
                            <span class="swiper-pagination-bullet"></span>
                            <span class="swiper-pagination-bullet"></span>
                        </div>
                    </div>

                    <div class="rt-swiper-navigation">
                        <div class="swiper-button-prev"></div>
                        <div class="swiper-button-next"></div>
                    </div>

                </div>

            </div>
        </div>
    </div>

<?php endif ?>