<?php
/**
 * Frontend template for: AZ Post Grid & Carousel
 * Expects $module with $module->settings (Beaver Builder style)
 */

if ( ! defined( 'ABSPATH' ) ) exit;

$settings    = isset($module->settings) ? $module->settings : (object)[];
$layout      = !empty($settings->layout_type) ? $settings->layout_type : 'carousel';
$post_type   = !empty($settings->post_type) ? $settings->post_type : 'post';
$post_count  = !empty($settings->posts_count) ? (int) $settings->posts_count : 6;
$module_id   = 'mod_' . sanitize_html_class( $module->node ?? uniqid() );
$module_slug = sanitize_html_class( $module->slug ?? 'az-post-grid' );

$paged_key  = 'az_paged_' . $module_id;
$paged      = isset($_GET[$paged_key]) ? max(1, (int) $_GET[$paged_key]) : 1;

$pagination_type = !empty($settings->pagination_type) ? $settings->pagination_type : 'numbers';
$taxonomy_filter = !empty($settings->category_filter) ? $settings->category_filter : '';

$yes = function($v){
  return !empty($v) && in_array((string)$v, ['1','true','yes','on'], true);
};

/** Helper: Category pills with optional links */
if ( ! function_exists('az_render_categories_pills') ) {
  function az_render_categories_pills( $post_id, $taxonomy, $link = true ) {
    $terms = get_the_terms( $post_id, $taxonomy );
    if ( empty($terms) || is_wp_error($terms) ) return '';
    $html = '<div class="az-cats">';
    foreach ( $terms as $t ) {
      $name = esc_html( $t->name );
      if ( $link ) {
        $url = get_term_link( $t );
        $html .= !is_wp_error($url)
          ? '<a class="az-cat" href="'. esc_url($url) .'">'. $name .'</a>'
          : '<span class="az-cat">'. $name .'</span>';
      } else {
        $html .= '<span class="az-cat">'. $name .'</span>';
      }
    }
    $html .= '</div>';
    return $html;
  }
}

/** Build the query */
$args = [
  'post_type'      => $post_type,
  'posts_per_page' => $post_count,
  'paged'          => $paged,
  'tax_query'      => [],
];

/** Order by */
switch ($settings->order_by ?? 'date_desc') {
  case 'date_asc':   $args['orderby']='date';  $args['order']='ASC';  break;
  case 'title_asc':  $args['orderby']='title'; $args['order']='ASC';  break;
  case 'title_desc': $args['orderby']='title'; $args['order']='DESC'; break;
  case 'rand':       $args['orderby']='rand';                       break;
  case 'date_desc':
  default:           $args['orderby']='date';  $args['order']='DESC'; break;
}

/** Woo: product_cat from module select (IDs) */
if ( $post_type === 'product' && !empty($settings->product_category) ) {
  $args['tax_query'][] = [
    'taxonomy' => 'product_cat',
    'field'    => 'term_id',
    'terms'    => (array) $settings->product_category,
  ];
}

/** Generic taxonomy filter from CSV slugs (posts/products) */
if (!empty($taxonomy_filter)) {
  $taxonomy = ($post_type === 'product') ? 'product_cat' : 'category';
  $terms = array_filter(array_map('trim', explode(',', $taxonomy_filter)));
  if ($terms) {
    $args['tax_query'][] = [
      'taxonomy' => $taxonomy,
      'field'    => 'slug',
      'terms'    => $terms,
    ];
  }
}

/** Woo: featured / on-sale */
if ($post_type === 'product') {
  if ($yes($settings->only_featured ?? null)) {
    $args['tax_query'][] = [
      'taxonomy' => 'product_visibility',
      'field'    => 'name',
      'terms'    => ['featured'],
      'operator' => 'IN',
    ];
  }
  if ($yes($settings->only_sale ?? null) && function_exists('wc_get_product_ids_on_sale')) {
    $args['post__in'] = wc_get_product_ids_on_sale();
  }
}

$loop = new WP_Query($args);

/** Determine taxonomy for pills */
$tax_for_pills = !empty($settings->taxonomy)
  ? sanitize_key($settings->taxonomy)
  : ( ($post_type === 'product') ? 'product_cat' : 'category' );
$show_cats   = $yes($settings->show_categories ?? null);
$link_cats   = $yes($settings->category_link ?? null);
$show_thumb  = $yes($settings->show_product_thumbnail ?? null);
$show_date   = $yes($settings->display_date ?? null);
$show_desc   = $yes($settings->show_description ?? null);
$show_price  = $yes($settings->show_product_price ?? null);
$show_cart   = $yes($settings->show_add_to_cart ?? null);
$loop_slides = $yes($settings->loop ?? null);
$do_autoplay = $yes($settings->autoplay ?? null);
$excerpt_len = (int) ($settings->excerpt_length ?? 20);
?>

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

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

  <div class="az-post-grid-wrapper <?php echo esc_attr($layout); ?>">

  <?php if ($layout === 'carousel') : ?>
    <div class="swiper az-swiper">
      <div class="swiper-wrapper">
        <?php while ($loop->have_posts()) : $loop->the_post(); ?>
          <?php
          $is_product = ($post_type === 'product');
          $product = null;
          if ($is_product && function_exists('wc_get_product')) {
            $product = wc_get_product(get_the_ID());
          }
          ?>
          <div class="swiper-slide">
            <?php if (has_post_thumbnail() && $show_thumb) : ?>
              <a target="_blank" href="<?php echo esc_url(get_permalink()); ?>">
                <?php if ($is_product && $product) : ?>
                  <?php
                  $gallery_ids = $product->get_gallery_image_ids();
                  $main_img = get_the_post_thumbnail(get_the_ID(), 'woocommerce_thumbnail', ['class' => 'main-image']);
                  $hover_img = '';
                  if (!empty($gallery_ids)) {
                    $hover_url = wp_get_attachment_image_url($gallery_ids[0], 'woocommerce_thumbnail');
                    if ($hover_url) {
                      $hover_img = '<img src="'. esc_url($hover_url) .'" class="hover-image" alt="" />';
                    }
                  }
                  echo '<div class="product-thumb-hover">'. $main_img . $hover_img .'</div>';
                  ?>
                <?php else : ?>
                  <div class="bg-featured" style="background-image:url('<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>');"></div>
                <?php endif; ?>
              </a>
            <?php endif; ?>

            <div class="content">
              <?php
              if ($show_cats) {
                echo az_render_categories_pills(get_the_ID(), $tax_for_pills, $link_cats);
              }
              ?>

              <?php if ($show_date) : ?>
                <p class="post-date"><?php echo esc_html(get_the_date('F j, Y')); ?></p>
              <?php endif; ?>

              <h5><a target="_blank" href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a></h5>

              <?php if ($show_desc) : ?>
                <p><?php echo esc_html( wp_trim_words(get_the_excerpt(), $excerpt_len) ); ?></p>
              <?php endif; ?>

              <?php if ($is_product && $product) : ?>
                <?php if ($show_price) : ?>
                  <div class="product-price"><?php echo wp_kses_post($product->get_price_html()); ?></div>
                <?php endif; ?>
                <?php if ($show_cart) : ?>
                  <a href="<?php echo esc_url( add_query_arg('add-to-cart', $product->get_id()) ); ?>"
                     class="button add_to_cart_button ajax_add_to_cart"
                     data-product_id="<?php echo esc_attr($product->get_id()); ?>">
                     <?php esc_html_e('Add to cart', 'woocommerce'); ?>
                  </a>
                <?php endif; ?>
              <?php endif; ?>

              <a class="icon" href="<?php echo esc_url(get_permalink()); ?>"><i class="fas fa-chevron-right" aria-hidden="true"></i></a>
            </div>
          </div>
        <?php endwhile; ?>
      </div>

      <div class="swiper-button-prev">
        <?php
          echo !empty($settings->prev_icon)
            ? '<i class="'. esc_attr($settings->prev_icon) .'"></i>'
            : esc_html__('Prev', 'textdomain');
        ?>
      </div>
      <div class="swiper-button-next">
        <?php
          echo !empty($settings->next_icon)
            ? '<i class="'. esc_attr($settings->next_icon) .'"></i>'
            : esc_html__('Next', 'textdomain');
        ?>
      </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function () {
      const root   = document.getElementById('<?php echo esc_js($module_id); ?>');
      if (!root) return;

      const slider = root.querySelector('.az-swiper');
      if (!slider || typeof Swiper === 'undefined') return;

      new Swiper(slider, {
        slidesPerView: 1,
        loop: <?php echo $loop_slides ? 'true' : 'false'; ?>,
        autoplay: <?php echo $do_autoplay ? '{ delay: 3000, disableOnInteraction: false, pauseOnMouseEnter: true }' : 'false'; ?>,
        spaceBetween: 50, /* adjust to taste */
        navigation: {
          nextEl: root.querySelector('.swiper-button-next'),
          prevEl: root.querySelector('.swiper-button-prev'),
        },
        breakpoints: {
          768:  { slidesPerView: 2 },
          1024: { slidesPerView: 4 }
        }
      });
    });
    </script>

  <?php else : /* GRID LAYOUT */ ?>
    <div class="az-grid-layout">
      <?php while ($loop->have_posts()) : $loop->the_post(); ?>
        <?php
        $is_product = ($post_type === 'product');
        $product = null;
        if ($is_product && function_exists('wc_get_product')) {
          $product = wc_get_product(get_the_ID());
        }
        ?>
        <div class="az-grid-item">
          <!-- Optional full-card overlay (position absolute via CSS) -->
          <a class="overlay" href="<?php echo esc_url(get_permalink()); ?>" aria-label="<?php echo esc_attr(get_the_title()); ?>"></a>

          <?php if (has_post_thumbnail() && $show_thumb) : ?>
            <?php if ($is_product && $product) : ?>
              <?php
              $gallery_ids = $product->get_gallery_image_ids();
              $main_img = get_the_post_thumbnail(get_the_ID(), 'woocommerce_thumbnail', ['class' => 'main-image']);
              $hover_img = '';
              if (!empty($gallery_ids)) {
                $hover_url = wp_get_attachment_image_url($gallery_ids[0], 'woocommerce_thumbnail');
                if ($hover_url) {
                  $hover_img = '<img src="'. esc_url($hover_url) .'" class="hover-image" alt="" />';
                }
              }
              echo '<div class="product-thumb-hover">'. $main_img . $hover_img .'</div>';
              ?>
            <?php else : ?>
              <div class="post-thumb">
                <div class="bg-featured" style="background-image:url('<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>');"></div>
              </div>
            <?php endif; ?>
          <?php endif; ?>

          <div class="content">
            <?php
            if ($show_cats) {
              echo az_render_categories_pills(get_the_ID(), $tax_for_pills, $link_cats);
            }
            ?>

            <?php if ($show_date) : ?>
              <p class="post-date"><?php echo esc_html(get_the_date('F j, Y')); ?></p>
            <?php endif; ?>

            <h4><a href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a></h4>

            <?php if ($show_desc) : ?>
              <p><?php echo esc_html( wp_trim_words(get_the_excerpt(), $excerpt_len) ); ?></p>
            <?php endif; ?>

            <?php if ($is_product && $product) : ?>
              <?php if ($show_price) : ?>
                <div class="product-price"><?php echo wp_kses_post($product->get_price_html()); ?></div>
              <?php endif; ?>
              <?php if ($show_cart) : ?>
                <a href="<?php echo esc_url( add_query_arg('add-to-cart', $product->get_id()) ); ?>"
                   class="button add_to_cart_button ajax_add_to_cart"
                   data-product_id="<?php echo esc_attr($product->get_id()); ?>">
                   <?php esc_html_e('Add to cart', 'woocommerce'); ?>
                </a>
              <?php endif; ?>
            <?php endif; ?>

            <a class="icon" href="<?php echo esc_url(get_permalink()); ?>"><i class="fas fa-chevron-right" aria-hidden="true"></i></a>
          </div>
        </div>
      <?php endwhile; ?>
    </div>

    <?php if ($pagination_type === 'numbers') : ?>
      <div class="az-pagination-numbers">
        <?php
        echo paginate_links([
          'total'     => (int) $loop->max_num_pages,
          'current'   => (int) $paged,
          'format'    => '?' . $paged_key . '=%#%',
          'prev_text' => esc_html__('« Prev', 'textdomain'),
          'next_text' => esc_html__('Next »', 'textdomain'),
        ]);
        ?>
      </div>

    <?php elseif ($pagination_type === 'load_more' && $loop->max_num_pages > 1) : ?>
      <div class="az-load-more-wrap">
        <button id="<?php echo esc_attr($module_id); ?>-load-more"
                data-page="1"
                data-max="<?php echo esc_attr($loop->max_num_pages); ?>">
          <?php echo !empty($settings->load_more_text) ? esc_html($settings->load_more_text) : esc_html__('Load More', 'textdomain'); ?>
        </button>
      </div>

      <script>
      document.addEventListener('DOMContentLoaded', function () {
        const btn  = document.getElementById('<?php echo esc_js($module_id); ?>-load-more');
        const wrap = document.querySelector('#<?php echo esc_js($module_id); ?> .az-grid-layout');
        if (!btn || !wrap) return;

        btn.addEventListener('click', function () {
          let page = parseInt(this.dataset.page, 10) + 1;
          const max = parseInt(this.dataset.max, 10);
          const url = '<?php echo esc_url( admin_url('admin-ajax.php') ); ?>?action=az_load_more_posts&page=' + page;

          fetch(url, { credentials: 'same-origin' })
            .then(res => res.text())
            .then(html => {
              wrap.insertAdjacentHTML('beforeend', html);
              this.dataset.page = page;
              if (page >= max) this.remove();
            })
            .catch(() => { /* show notice if you want */ });
        });
      });
      </script>
    <?php endif; ?>

  <?php endif; /* end grid/carousel */ ?>

  </div>
</section>

<?php wp_reset_postdata(); ?>
