<?php
$settings        = $module->settings;
$module_slug     = sanitize_html_class( $module->slug );
$filter_enabled  = ( isset($settings->enable_filter) && $settings->enable_filter === 'yes' );

// Resolve primary taxonomy (if any) for the chosen post type.
$taxonomies  = get_object_taxonomies( $settings->post_type );
$primary_tax = ! empty( $taxonomies ) ? $taxonomies[0] : null;

// Build list of category slugs from settings.
$category_slugs = [];
if ( $filter_enabled && ! empty( $settings->categories ) ) {
    $category_slugs = array_map( 'trim', explode( ',', $settings->categories ) );
} elseif ( ! $filter_enabled && ! empty( $settings->single_category ) ) {
    $category_slugs = [ trim( $settings->single_category ) ];
}

// Build tax query only when a real taxonomy exists and slugs provided.
$tax_query = [];
if ( $primary_tax && taxonomy_exists( $primary_tax ) && ! empty( $category_slugs ) ) {
    $tax_query[] = [
        'taxonomy' => $primary_tax,
        'field'    => 'slug',
        'terms'    => $category_slugs,
    ];
}

$posts_per_page = isset( $settings->posts_per_page ) ? absint( $settings->posts_per_page ) : 6;
$paged          = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

$args = [
    'post_type'      => $settings->post_type,
    'post_status'    => 'publish',
    'posts_per_page' => $posts_per_page,
    'paged'          => $paged,
];
if ( ! empty( $tax_query ) ) {
    $args['tax_query'] = $tax_query;
}

$query = new WP_Query( $args );




?>

<link rel="stylesheet" href="<?php echo esc_url( $module->url . 'css/az-post-grid-filtering.css' ); ?>" />

<section id="module-<?php echo esc_attr( $module->slug ); ?>"
         class="<?php echo esc_attr( $module->slug ); ?>"
         data-module="<?php echo esc_attr( $module_slug ); ?>">

  <?php if ( $filter_enabled && $primary_tax && ! empty( $category_slugs ) ) : ?>
    <div class="az-category-scroll-wrapper">
      <button class="az-scroll-left" aria-label="Scroll left"><i class="fas fa-chevron-left"></i></button>

      <div class="az-category-filter">
        <button class="az-filter-btn active" data-cat="all"><?php esc_html_e('All','fl-builder'); ?></button>
        <?php foreach ( $category_slugs as $cat_slug ) :
          $term = get_term_by( 'slug', $cat_slug, $primary_tax );
          if ( $term ) : ?>
            <button class="az-filter-btn" data-cat="<?php echo esc_attr( $term->slug ); ?>">
              <?php echo esc_html( $term->name ); ?>
            </button>
          <?php endif;
        endforeach; ?>
      </div>

      <button class="az-scroll-right" aria-label="Scroll right"><i class="fas fa-chevron-right"></i></button>
    </div>
  <?php endif; ?>

  <div class="az-post-list"
       data-paged="<?php echo esc_attr( $paged ); ?>"
       data-max="<?php echo esc_attr( $query->max_num_pages ); ?>">

    <?php if ( $query->have_posts() ) : ?>
      <?php while ( $query->have_posts() ) : $query->the_post();
        // Build data-cats only when we have a valid taxonomy
        $term_slugs = [];
        if ( $primary_tax ) {
          $term_slugs = wp_get_post_terms( get_the_ID(), $primary_tax, [ 'fields' => 'slugs' ] );
        }

        $thumb_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
      ?>
        <article class="az-post-item" data-cats="<?php echo esc_attr( implode( ' ', $term_slugs ) ); ?>">
          <a href="<?php the_permalink(); ?>">
            <div class="box-image">
              <?php if ( $thumb_url ) : ?>
                <div class="az-post-thumb image-bg" style="background-image:url('<?php echo esc_url( $thumb_url ); ?>');"></div>
              <?php else : ?>
                <!-- Fallback when no thumbnail (ACF CPTs often lack thumbnails) -->
                <div class="az-post-thumb no-thumb"></div>
              <?php endif; ?>
              <p class="az-post-title"><?php the_title(); ?></p>
            </div>
          </a>
        </article>
      <?php endwhile; ?>
    <?php else : ?>
      <p class="az-no-posts"><?php esc_html_e( 'No posts found.', 'fl-builder' ); ?></p>
    <?php endif; ?>
  </div>

  <?php if ( isset($settings->load_mode) && $settings->load_mode === 'load_more' && $query->max_num_pages > 1 ) : ?>
    <div class="az-load-more-wrap">
      <button class="az-load-more-btn" data-module="<?php echo esc_attr( $module_slug ); ?>">
        <?php esc_html_e( 'Load More', 'fl-builder' ); ?>
      </button>
    </div>
  <?php endif; ?>

  <?php if ( isset($settings->load_mode) && $settings->load_mode === 'pagination' ) : ?>
    <div class="az-pagination">
      <?php
        echo paginate_links( [
          'total'   => $query->max_num_pages,
          'current' => $paged,
        ] );
      ?>
    </div>
  <?php endif; ?>

  <?php wp_reset_postdata(); ?>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  // Only activate scroll buttons below 768px
  if (window.innerWidth > 768) return;
  const wrapper = document.querySelector('.az-category-scroll-wrapper');
  if (!wrapper) return;
  const container = wrapper.querySelector('.az-category-filter');
  const btnLeft = wrapper.querySelector('.az-scroll-left');
  const btnRight = wrapper.querySelector('.az-scroll-right');
  const scrollAmount = 100;
  btnLeft.addEventListener('click', () => container.scrollBy({ left: -scrollAmount, behavior: 'smooth' }));
  btnRight.addEventListener('click', () => container.scrollBy({ left:  scrollAmount, behavior: 'smooth' }));
});
</script>

<script>
window.azPostFilterSettings = <?php echo wp_json_encode( [
  'ajax_url' => admin_url( 'admin-ajax.php' ),
  'settings' => $settings,
] ); ?>;
</script>
<script src="<?php echo esc_url( $module->url . 'js/az-post-grid-filtering.js' ); ?>"></script>
