<?php 
    if (isset($block['data']['isExample']) && $block['data']['isExample']) {
        echo '<img src="' . esc_url( $block['data']['preview_image'] ) . '"style="max-width:100%; min-width:100%" alt="Preview" />';
        return;
    }

    global $rdgb;
    $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

    $block_styles = [];
    $block_classes = [];
    $block_name = BLOCK_RDG_CAROUSEL;
    $block_classes = [$block_name];
    $block_carousel = $rdgb->settings->getBlock($block_name);

    if (!empty($block['backgroundColor'])) {
        $block_classes[] = 'has-background';
        $block_classes[] = 'has-'.$block['backgroundColor'].'-background-color';
    }

    if (!empty($block['style']['color']['background'])) {
        $block_styles[] = 'background-color: '.$block['style']['color']['background'].';';
    }

    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());

    $post_type = get_field('post_type');
    $quantity = get_field('quantity');
    $order_by = get_field('order_by');
    $order = get_field('order');
    $fallback_url = '';
    $block_fallback_image = get_field('fallback_image');
    if (is_array($block_fallback_image) && !empty($block_fallback_image) && isset($block_fallback_image['url']) && !empty($block_fallback_image['url'])) {
        $fallback_url = htmlspecialchars($block_fallback_image['url'], ENT_QUOTES, 'UTF-8');
    }

?>

<div class="rdg-blocks">
    <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
        <div class="wrapper container grid-container">
            <button id="left" class="carousel-btn left">
                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 60 60" fill="none">
                    <path d="M33.606 21.947L24.891 30.6245L33.606 39.302" stroke="#3469AB" stroke-width="2" stroke-linecap="square"/>
                </svg>
            </button>
            <div class="carousel">
                <?php
                $args = array(
                    'post_type' => $post_type, 
                    'posts_per_page' => $quantity, 
                    'orderby' => $order,
                    'order' => $order_by
                );
            
                $the_query = new WP_Query( $args );

                while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 
                    <div class="carousel-item" draggable="false">
                        <div class="featured-img">
                            <a href="<?php echo get_permalink(); ?>">
                                <?php
                                    $thumbnail_id = get_post_thumbnail_id();
                                    $thumbnail_url = wp_get_attachment_url($thumbnail_id);                                  
                                                                
                                    the_post_thumbnail('full', array(
                                        'class' => 'post-thumbnail',
                                        'data-fallback' => esc_url($fallback_url),
                                        'data-original-src' => esc_url($thumbnail_url),
                                        'onerror' => "this.onerror=null; this.src=this.getAttribute('data-fallback');"
                                    ));
                                ?>
                            </a>
                        </div>
                        <p class="date"><?php echo get_the_modified_date(); ?></p>
                        <a href="<?php echo get_permalink(); ?>" class="title"><?php the_title(); ?></a>
                        <p class="excerpt"><?php echo wp_trim_words( get_the_excerpt(), 30, '' ); ?></p>
                    </div>
                <?php endwhile;
                wp_reset_postdata();        
                ?>
            </div>
            <button id="right" class="carousel-btn right">
                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 60 60" fill="none">
                <path d="M26.394 38.053L35.109 29.3755L26.394 20.698" stroke="#3469AB" stroke-width="2" stroke-linecap="square"/>
                </svg>
            </button>
        </div>
    </div>
    <script>

        document.querySelectorAll('.post-thumbnail').forEach(img => {            
            const originalSrc = img.getAttribute('data-original-src');
            if (originalSrc) {
                img.src = originalSrc;
                img.removeAttribute('srcset');
                img.removeAttribute('sizes');
            }

            img.addEventListener('error', function() {
                this.onerror = null;
                this.src = this.getAttribute('data-fallback');
            });
        })

        const carousel= document.querySelector('.carousel');
        firstItem = carousel.querySelectorAll('.carousel-item')[0];
        const arrowIcons= document.querySelectorAll('.wrapper .carousel-btn');

        let isDragStart = false, prevPageX, prevScrollLeft, positionDiff;

        const showHideIcons = () => {
            let scrollWidth = carousel.scrollWidth - carousel.clientWidth;
            arrowIcons[0].style.display = carousel.scrollLeft == 0 ? 'none' : 'grid';
            arrowIcons[1].style.display = carousel.scrollLeft == scrollWidth ? 'none' : 'grid';
        }

        arrowIcons.forEach(icon => {
            icon.addEventListener('click', () => {
                let firstItemWidth = firstItem.clientWidth + 32;
                carousel.scrollLeft += icon.id == 'left' ? -firstItemWidth : firstItemWidth;
                setTimeout(() => showHideIcons(), 60);
            });
        });

        const dragStart = (e) => {
            isDragStart = true;
            prevPageX = e.pageX || e.touches[0].pageX;
            prevScrollLeft = carousel.scrollLeft;
        }

        const dragging = (e) => {
            if(!isDragStart) return;
            e.preventDefault();
            carousel.classList.add('dragging');
            positionDiff = (e.pageX || e.touches[0].pageX) - prevPageX;
            carousel.scrollLeft = prevScrollLeft - positionDiff;
            showHideIcons();
        }

        const dragStop = () => {
            isDragStart = false;
            carousel.classList.remove('dragging');
        }

        carousel.addEventListener('mousedown', dragStart);
        carousel.addEventListener('touchstart', dragStart);

        carousel.addEventListener('mousemove', dragging);
        carousel.addEventListener('touchmove', dragging);

        carousel.addEventListener('mouseup', dragStop);
        carousel.addEventListener('mouseleave', dragStop);
        carousel.addEventListener('touchend', dragStop);
    </script>
</div>
