<?php

namespace Lknwp\CrowdfundingExtension\Includes;

use WP_Query;

defined('ABSPATH') || exit;

final class LknwpCrowdfundingExtensionListingPage
{
    public function lkn_listing_callback($atts, $shortcode)
    {
        if (function_exists('wpcf_function')) {

            //num foi trocado por max
            $a = shortcode_atts(
                array(
                    'cat'   => null,
                    'order' => 'DESC',
                    'max'   => null,
                ),
                $atts,
                $shortcode
            );

            $posts_per_page = !empty($a['max']) ? intval($a['max']) : 10;

            $paged = max(1, get_query_var('paged', get_query_var('page', 1)));

            $query_args = array(
                'post_type'      => 'product',
                'post_status'    => 'publish',
                'tax_query'      => array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'product_type',
                        'field'    => 'slug',
                        'terms'    => 'crowdfunding',
                    ),
                ),
                'posts_per_page' => $posts_per_page,
                'paged'          => $paged,
                'orderby'        => 'post_title',
                'order'          => $a['order'],
            );

            if ($a['cat']) {
                $cat_array                 = explode(',', $a['cat']);
                $query_args['tax_query'][] = array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => $cat_array,
                );
            }

            // Instanciando o WP_Query
            $custom_query = new WP_Query($query_args);

            // Preparando o WP_Query global
            global $wp_query;
            $original_query = $wp_query; // Armazena o estado original
            $wp_query = $custom_query;  // Sobrescreve o global com o WP_Query personalizado

            ob_start();
            wpcf_function()->template('wpneo-listing');
            $html = ob_get_clean();

            // Restaura o $wp_query global
            $wp_query = $original_query;
            wp_reset_postdata();

            return $html;
        }
    }
}
