<?php
/**
 * 
 * @package tx
 * @author theme-x
 * @link https://theme-x.org/

/* ---------------------------------------------------------
  Project carousel
------------------------------------------------------------ */


$count = tx_get_option( 'project-exp-count', 8 );

$q = new WP_Query( [
    'post_type'      => 'portfolio',
    'posts_per_page' => $count,
    'post_status'    => 'publish',
    'orderby'        => 'rand',
    'no_found_rows'  => true, // perf
] );

if ( $q->have_posts() ) :

    // enqueue Owl only when we actually render the carousel
    wp_enqueue_style(  'tx-owl-carousel' );
    wp_enqueue_script( 'tx-owl-carousel' );

    // unique id to support multiple instances on one page
    $carousel_id = 'project-carousel-' . wp_rand();
    ?>
    <div id="<?php echo esc_attr( $carousel_id ); ?>" class="project-carousel owl-carousel">
        <?php while ( $q->have_posts() ) : $q->the_post(); ?>
            <div class="item">
                <figure>
                    <a href="<?php the_permalink(); ?>" rel="bookmark">
                        <?php
                        if ( has_post_thumbnail() ) {
                            the_post_thumbnail( 'tx-pe-thumb' );
                        }
                        ?>
                    </a>
                    <figcaption>
                        <h4><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h4>
                    </figcaption>
                </figure>
            </div>
        <?php endwhile; ?>
    </div>
    <?php
    wp_reset_postdata();

    // init owl AFTER your theme main script so nothing overrides it
    $init_js = <<<JS
    jQuery(function($){
      var \$el = $('#{$carousel_id}');

      if (\$el.hasClass('owl-loaded')) {
        // already initialized by something else – destroy and clean
        \$el.trigger('destroy.owl.carousel');
        \$el.find('.owl-stage-outer').children().unwrap();
        \$el.removeClass('owl-loaded owl-hidden');
      }

      \$el.owlCarousel({
        loop: true,
        margin: 20,
        nav: true,
        dots: false,
        autoplay: true,
        autoplayTimeout: 3000,
        smartSpeed: 600,
        navText: ['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>'],
        responsive: {
          0:    { items: 1 },
          600:  { items: 2 },
          1000: { items: 4 }   // desktop = 3
        }
      });
    });
    JS;

    // attach after your main script so later scripts don’t override settings
    if ( wp_script_is( 'tx-main-scripts', 'enqueued' ) ) {
        wp_add_inline_script( 'tx-main-scripts', $init_js, 'after' );
    } else {
        // fallback: attach after owl if main script isn't present here
        wp_add_inline_script( 'tx-owl-carousel', $init_js, 'after' );
    }

else :
    echo '<p>' . esc_html__( 'Sorry, nothing found.', 'avas' ) . '</p>';
endif;
