<?php

namespace Lknwp\CrowdfundingExtension\Includes\elementorFields\database;

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

class LknwpCrowdfundingListingQuery
{
    public static function getQuery($settings, $offset = 0)
    {
        $query_args = [
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => !empty($settings['number']) ? $settings['number'] : 10,
            'orderby'        => 'post_title',
            'order'          => ($settings['order'] === 'RAND') ? 'DESC' : $settings['order'],
            'offset'         => $offset,
            'tax_query'      => [
                [
                    'taxonomy' => 'product_type',
                    'field'    => 'slug',
                    'terms'    => 'crowdfunding',
                ],
            ],
        ];

        if (!empty($settings['category'])) {
            $cat_array = explode(',', $settings['category']);
            $query_args['tax_query'][] = [
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $cat_array,
            ];
        }

        $query = new \WP_Query($query_args);

        if ($settings['order'] === 'RAND' && !empty($query->posts)) {
            shuffle($query->posts);
        }

        return $query;
    }
}
