<?php
// ACF fields
$post_type       = get_field('post_type') ?: 'vins';
$posts_per_page  = (int) (get_field('posts_per_page') ?: 6);
$columns         = (int) (get_field('columns') ?: 3); // 2,3,4
$order           = get_field('order') ?: 'DESC';
$order_by        = get_field('order_by') ?: 'date';
$tax_name        = get_field('taxonomy'); // e.g., 'category' or custom taxonomy
$tax_terms_raw   = trim((string) get_field('terms'));
$offset          = (int) (get_field('offset') ?: 0);
// Manual selection overrides query if provided
$selected_posts  = get_field('selected_posts'); // array of IDs

// Sanitize/normalize
$columns = in_array($columns, array(2, 3, 4), true) ? $columns : 3;
$order   = in_array($order, array('ASC', 'DESC'), true) ? $order : 'DESC';
$order_by = $order_by ?: 'date';

// Build WP_Query args
if (is_array($selected_posts) && !empty($selected_posts)) {
  // Respect posts_per_page if defined
  if ($posts_per_page > 0) {
    $selected_posts = array_slice($selected_posts, 0, $posts_per_page);
  }
  $args = array(
    'post_type'      => $post_type,
    'post__in'       => $selected_posts,
    'orderby'        => 'post__in', // preserve manual order
    'posts_per_page' => count($selected_posts),
    'post_status'    => 'publish',
    'suppress_filters' => false,
  );
} else {
  $args = array(
    'post_type'      => $post_type,
    'posts_per_page' => $posts_per_page,
    'orderby'        => $order_by,
    'order'          => $order,
    'offset'         => $offset,
    'post_status'    => 'publish',
    'suppress_filters' => false,
  );

  if ($tax_name && $tax_terms_raw) {
    $terms = array_filter(array_map('trim', explode(',', $tax_terms_raw)));
    if (!empty($terms)) {
      $args['tax_query'] = array(
        array(
          'taxonomy' => $tax_name,
          'field'    => is_numeric($terms[0]) ? 'term_id' : 'slug',
          'terms'    => $terms,
        )
      );
    }
  }
}

$query = new WP_Query($args);

// CSS classes
$grid_cols = array(
  2 => 'grid-cols-2 sm:grid-cols-2',
  3 => 'grid-cols-2 sm:grid-cols-2 lg:grid-cols-3',
  4 => 'grid-cols-2 sm:grid-cols-2 lg:grid-cols-4',
);
$grid_class = isset($grid_cols[$columns]) ? $grid_cols[$columns] : $grid_cols[3];

// Helper to get featured image (guard against redeclaration if template is loaded multiple times)
if (!function_exists('lp_cards_grid_thumb')) {
  function lp_cards_grid_thumb($post_id)
  {
    //
    $img = get_field('image_carrousel_v2', $post_id);

    if (!empty($img) && is_array($img)) {
      return wp_get_attachment_image($img['id'], 'large', false, array('class' => 'w-full h-full object-cover absolute top-0 left-0 z-0 group-hover:scale-110 transition-transform ease-out duration-700 '));
    } elseif (has_post_thumbnail($post_id)) {
      return get_the_post_thumbnail($post_id, 'large', array('class' => 'w-full h-full object-cover absolute top-0 left-0 z-0 group-hover:scale-110 transition-transform ease-out duration-700 '));
    } else {
      return '';
    }
  }
}
?>

<?php if ($query->have_posts()): ?>
  <div class="lp-cards-grid">
    <div class="lp-cards-grid__grid grid gap-4 <?php echo esc_attr($grid_class); ?>">
      <?php if ($query->have_posts()): while ($query->have_posts()): $query->the_post(); ?>
          <article class="lp-cards-grid__card group">
            <a href="<?php the_permalink(); ?>" class="block group-hover:!no-underline !text-black ">
              <div class="lp-cards-grid__media aspect-[3/4] relative overflow-hidden">
                <?php echo lp_cards_grid_thumb(get_the_ID()); ?>
              </div>
              <div class="lp-cards-grid__title heading-text mt-4 text-center "><?php the_title(); ?></div>
            </a>
          </article>
        <?php endwhile;
        wp_reset_postdata(); ?>
      <?php endif; ?>
    </div>
  </div>
<?php endif; ?>
