<?php
/**
 * WooCommerce helpers and fragments.
 *
 * @package SeedProd
 * @subpackage SeedProd/app
 */



/**
 * WooCommerce Cart fragment.
 *
 * @see seedprod_pro_cart_link_fragment()
 */
add_filter( 'woocommerce_add_to_cart_fragments', 'seedprod_pro_cart_link_fragment' );

if ( ! function_exists( 'seedprod_pro_woo_cart_available' ) ) {
	/**
	 * Validates whether the Woo Cart instance is available in the request
	 *
	 * @since 2.6.0
	 * @return boolean
	 */
	function seedprod_pro_woo_cart_available() {
		if ( ! function_exists( 'WC' ) ) {
			return false;
		}
		$woo = WC();
		return $woo instanceof \WooCommerce && $woo->cart instanceof \WC_Cart;
	}
}

if ( ! function_exists( 'seedprod_pro_cart_link_fragment' ) ) {
	/**
	 * Cart fragment.s
	 * Ensure cart contents update when products are added to the cart via AJAX.
	 *
	 * @param  array $fragments Fragments to refresh via AJAX.
	 * @return array            Fragments to refresh via AJAX
	 */
	function seedprod_pro_cart_link_fragment( $fragments ) {
		global $woocommerce;

		ob_start();
		seedprod_pro_cart_link();
		$fragments['span.sp-menu-cart-item-count'] = ob_get_clean();

		ob_start();
		seedprod_pro_cart_items_total();
		$fragments['span.sp-menu-cart-button-text'] = ob_get_clean();

		return $fragments;
	}
}

if ( ! function_exists( 'seedprod_pro_cart_link' ) ) {
	/**
	 * Cart Link
	 * Displayed a link to the cart including the number of items present and the cart total
	 *
	 * @return void
	 * @since  1.0.0
	 */
	function seedprod_pro_cart_link() {
		if ( ! seedprod_pro_woo_cart_available() ) {
			return;
		}
		?>
			<span class="sp-text-xs sp-text-white sp-bg-red sp-menu-cart-item-count">
				<?php echo wp_kses_post( WC()->cart->get_cart_contents_count() ); ?>
			</span>
		<?php
	}
}

if ( ! function_exists( 'seedprod_pro_cart_items_total' ) ) {
	/**
	 * Cart Link
	 * Displayed a link to the cart including the number of items present and the cart total
	 *
	 * @return void
	 * @since  1.0.0
	 */
	function seedprod_pro_cart_items_total() {
		if ( ! seedprod_pro_woo_cart_available() ) {
			return;
		}
		?>
			<span class="sp-menu-cart-button-text">
				<?php echo wp_kses_post( WC()->cart->get_cart_subtotal() ); ?>
			</span>
		<?php
	}
}

/**
 * Render WooCommerce Custom Products Grid Shortcode for Builder Preview
 */
function seedprod_pro_render_shortcode_wc_custom_products_grid() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		$cols           = isset( $_GET['cols'] ) ? sanitize_text_field( wp_unslash( $_GET['cols'] ) ) : '';
		$paginate       = isset( $_GET['paginate'] ) ? sanitize_text_field( wp_unslash( $_GET['paginate'] ) ) : '';
		$limit          = isset( $_GET['limit'] ) ? sanitize_text_field( wp_unslash( $_GET['limit'] ) ) : '';
		$order_by       = isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : '';
		$order          = isset( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : '';
		$skus           = isset( $_GET['skus'] ) ? sanitize_text_field( wp_unslash( $_GET['skus'] ) ) : '';
		$ids            = isset( $_GET['ids'] ) ? sanitize_text_field( wp_unslash( $_GET['ids'] ) ) : '';
		$category       = isset( $_GET['category'] ) ? sanitize_text_field( wp_unslash( $_GET['category'] ) ) : '';
		$tag            = isset( $_GET['tag'] ) ? sanitize_text_field( wp_unslash( $_GET['tag'] ) ) : '';
		$product_group  = isset( $_GET['product_group'] ) ? sanitize_text_field( wp_unslash( $_GET['product_group'] ) ) : ''; // Options - on_sale, best_selling, top_rated.
		$attribute      = isset( $_GET['attribute'] ) ? sanitize_text_field( wp_unslash( $_GET['attribute'] ) ) : '';
		$terms          = isset( $_GET['terms'] ) ? sanitize_text_field( wp_unslash( $_GET['terms'] ) ) : '';
		$terms_operator = isset( $_GET['terms_operator'] ) ? sanitize_text_field( wp_unslash( $_GET['terms_operator'] ) ) : '';
		$tag_operator   = isset( $_GET['tag_operator'] ) ? sanitize_text_field( wp_unslash( $_GET['tag_operator'] ) ) : '';
		$cat_operator   = isset( $_GET['cat_operator'] ) ? sanitize_text_field( wp_unslash( $_GET['cat_operator'] ) ) : '';
		$visibility     = isset( $_GET['visibility'] ) ? sanitize_text_field( wp_unslash( $_GET['visibility'] ) ) : '';
		$source         = isset( $_GET['source'] ) ? sanitize_text_field( wp_unslash( $_GET['source'] ) ) : '';
		$group_attr     = '';

		if ( '' !== $product_group ) {
			$group_attr = $product_group . "='true'";
		}

		if ( 'all_products' === $source ) {
			echo do_shortcode( "[products paginate='$paginate' limit='$limit' columns='$cols' orderby='$order_by' order='$order' ]" );
		}

		if ( 'featured_products' === $source ) {
			echo do_shortcode( "[products visibility='featured' paginate='$paginate' limit='$limit' columns='$cols' ]" );
		}

		if ( 'sale_products' === $source ) {
			echo do_shortcode( "[products orderby='popularity' on_sale='true' paginate='$paginate' limit='$limit' columns='$cols' ]" );
		}

		if ( 'best_selling_products' === $source ) {
			echo do_shortcode( "[products best_selling='true' paginate='$paginate' limit='$limit' columns='$cols' ]" );
		}

		if ( 'recent_products' === $source ) {
			echo do_shortcode( "[products orderby='id' order='DESC' visibility='visible' paginate='$paginate' limit='$limit' columns='$cols']" );
		}

		if ( 'top_rated_products' === $source ) {
			echo do_shortcode( "[products orderby='popularity' top_rated='true' paginate='$paginate' limit='$limit' columns='$cols']" );
		}

		if ( 'custom_query' === $source ) {
			echo do_shortcode( "[products columns='$cols' paginate='$paginate' limit='$limit' orderby='$order_by' order='$order' ids='$ids' skus='$skus' category='$category' tag='$tag' $group_attr attribute='$attribute' terms='$terms' terms_operator='$terms_operator' tag_operator='$tag_operator' cat_operator='$cat_operator' visibility='$visibility']" );
		}

		if ( 'archive_products' === $source ) {
			echo do_shortcode( "[sp_archive_products columns='$cols' paginate='$paginate' limit='$limit' orderby='$order_by' order='$order' skus='$skus' category='$category' tag='$tag' group_attr='$group_attr' attribute='$attribute' terms='$terms' terms_operator='$terms_operator' tag_operator='$tag_operator' cat_operator='$cat_operator' visibility='$visibility']" );
		}

		exit;
	}
}

/**
 * Get WooCommerce Products.
 *
 * @return JSON object.
 */
function seedprod_pro_get_woocommerce_products() {
	$products = array();

	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		// Check if Woocommmerce is installed and active.
		if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {
			// Fetch Products.
			$args = array(
				'status'   => 'publish',
				'limit'    => -1,
				'paginate' => false,
			);

			$p = wc_get_products( $args );

			foreach ( $p as $product ) {
				$products[] = $product->get_data();
			}
		}
	}

	wp_send_json( $products );
}

/**
 * Get product taxonomy.
 *
 * @return JSON object.
 */
function seedprod_pro_get_woocommerce_product_taxonomy() {
	$taxonomy = array();

	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		// Check if Woocommmerce is installed and active.
		if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {
			// Fetch taxonomy.
			$args = array(
				'taxonomy'   => isset( $_GET['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_GET['taxonomy'] ) ) : '',
				'hide_empty' => false,
			);

			$taxonomy = get_terms( $args );
		}
	}

	wp_send_json( $taxonomy );
}

/**
 * Get list of product attributes
 *
 * @return JSON object.
 */
function seedprod_pro_get_woocommerce_product_attributes() {
	$attributes = array();

	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		// Check if Woocommmerce is installed and active.
		if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {
			$attributes = wc_get_attribute_taxonomies();
		}
	}

	wp_send_json( $attributes );
}

/**
 * Get list of product attribute terms.
 *
 * @return JSON object.
 */
function seedprod_pro_get_woocommerce_product_attribute_terms() {
	$attribute_terms = array();

	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		// Check if Woocommmerce is installed and active.
		if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {
			$attribute = isset( $_GET['attribute'] ) ? sanitize_text_field( wp_unslash( $_GET['attribute'] ) ) : '';

			// Get attribute terms.
			if ( $attribute ) {
				$attribute_terms = get_terms(
					array(
						'taxonomy'   => 'pa_' . $attribute,
						'hide_empty' => false,
					)
				);
			}
		}
	}

	wp_send_json( $attribute_terms );
}

/**
 * Render WooCommerce Checkout Shortcode for Builder Preview
 */
function seedprod_pro_render_shortcode_wc_checkout() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		// Prevent redirect if cart is empty for preview.
		add_filter( 'woocommerce_checkout_redirect_empty_cart', '__return_false' );
		add_filter( 'woocommerce_checkout_update_order_review_expired', '__return_false' );

		echo do_shortcode( '[woocommerce_checkout]' );
		exit;
	}
}

/**
 * Render WooCommerce Cart Shortcode for Builder Preview
 */
function seedprod_pro_render_shortcode_wc_cart() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {
		if ( ! current_user_can( apply_filters( 'seedprod_builder_preview_render_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		echo do_shortcode( '[woocommerce_cart]' );
		exit;
	}
}

// Add [sp_archive_products] shortcode.
add_shortcode( 'sp_archive_products', 'seedprod_pro_woocommerce_template_tags_archive_products_shortcode' );

/**
 * Archive Products Shortcode function.
 *
 * @param array $atts Shortcode attributes.
 * @return string|void $render Html render.
 */
function seedprod_pro_woocommerce_template_tags_archive_products_shortcode( $atts ) {
	global $wp_query;

	// Set default shortcode args.
	$shortcode_args = shortcode_atts(
		array(
			'columns'        => '',
			'paginate'       => '',
			'limit'          => '',
			'orderby'        => '',
			'order'          => '',
			'skus'           => '',
			'category'       => '',
			'tag'            => '',
			'group_attr'     => '',
			'attribute'      => '',
			'terms'          => '',
			'terms_operator' => '',
			'tag_operator'   => '',
			'cat_operator'   => '',
			'visibility'     => '',
		),
		$atts
	);

	// Check if the WC Instance exists.
	if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {
		return;
	}

	// Get current product.
	$render    = '';
	$ids_array = array();

	// Get URL parameters.
	$min_price = isset( $_GET['min_price'] ) ? sanitize_text_field( wp_unslash( $_GET['min_price'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$max_price = isset( $_GET['max_price'] ) ? sanitize_text_field( wp_unslash( $_GET['max_price'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

	// Create custom query.
	$args = array(
		'post_type'           => 'product',
		'post_status'         => 'publish',
		'ignore_sticky_posts' => true,
		'posts_per_page'      => -1, // Fetch all posts in this query
		'orderby'             => $shortcode_args['orderby'],
		'order'               => $shortcode_args['order'],
		'meta_query'          => array(), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		'tax_query'           => array(), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
	);

	// Price range filter.
	if ( '' !== $min_price && '' !== $max_price ) {
		$args['meta_query'][] = array(
			'key'     => '_price',
			'value'   => array( $min_price, $max_price ),
			'type'    => 'NUMERIC',
			'compare' => 'BETWEEN',
		);
	}

	// Dynamic attribute filters.
	foreach ( $_GET as $param => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		// Check if the parameter is a filter for a product attribute.
		if ( strpos( $param, 'filter_' ) === 0 ) {
			$terms_val_array = explode( ',', $value );
			$attribute_name  = substr( $param, 7 );

			$default_query_type = 'and'; // Set a default query type.
			$query_type_param   = 'query_type_' . $attribute_name;
			$query_type         = $default_query_type;

			if ( count( $terms_val_array ) > 1 ) {
				$query_type         = isset( $_GET[ $query_type_param ] ) ? sanitize_text_field( wp_unslash( $_GET[ $query_type_param ] ) ) : $default_query_type; // phpcs:ignore
				$query_type         = in_array( strtolower( $query_type ), array( 'and', 'or' ) ) ? strtolower( $query_type ) : $default_query_type; // phpcs:ignore
			}

			$args['tax_query'][] = array(
				'taxonomy' => 'pa_' . $attribute_name,
				'field'    => 'slug',
				'terms'    => $terms_val_array,
				'operator' => 'or' === $query_type ? 'IN' : 'AND',
			);
		}

		// Check for orderby parameter.
		if ( 'orderby' === $param ) {
			$shortcode_args['orderby'] = sanitize_text_field( wp_unslash( $value ) );

			// Set default order for date - DESC.
			// This is for when 'Latest' is selected in the sort dropdown.
			if ( 'date' === $value ) {
				$shortcode_args['order'] = 'DESC';
			}
		}

		// Check for order parameter.
		if ( 'order' === $param ) {
			$shortcode_args['order'] = strtoupper( sanitize_text_field( wp_unslash( $value ) ) );
		}
	}

	// Set category & tags for archive page.
	// Fetch from current query.
	$archive_taxonomy = $wp_query->get_queried_object();
	if ( $archive_taxonomy instanceof \WP_Term && isset( $archive_taxonomy->taxonomy ) && isset( $archive_taxonomy->term_id ) ) {
		$args['tax_query']['relation'] = 'AND';
		$args['tax_query'][]           = array(
			'taxonomy' => $archive_taxonomy->taxonomy,
			'field'    => 'term_id',
			'terms'    => array( $archive_taxonomy->term_id ),
		);
	}

	// Set search partameter.
	if ( isset( $_GET['s'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$args['s'] = sanitize_text_field( wp_unslash( $_GET['s'] ) ); // phpcs:ignore
	}

	$query = new WP_Query( $args );

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();

			$id      = get_the_ID();
			$product = wc_get_product( $id );

			if ( ! $product ) {
				return;
			}

			array_push( $ids_array, $id );
		}
	}

	wp_reset_postdata();

	$ids = ! empty( $ids_array ) ? implode( ',', $ids_array ) : '0';

	ob_start();
	if ( '0' !== $ids ) {
		echo do_shortcode( "[products columns='$shortcode_args[columns]' paginate='$shortcode_args[paginate]' limit='$shortcode_args[limit]' orderby='$shortcode_args[orderby]' order='$shortcode_args[order]' ids='$ids' skus='$shortcode_args[skus]' category='$shortcode_args[category]' tag='$shortcode_args[tag]' $shortcode_args[group_attr] attribute='$shortcode_args[attribute]' terms='$shortcode_args[terms]' terms_operator='$shortcode_args[terms_operator]' tag_operator='$shortcode_args[tag_operator]' cat_operator='$shortcode_args[cat_operator]' visibility='$shortcode_args[visibility]']" );
	} else {
		echo esc_html__( 'No products matching your selection were found.', 'seedprod-pro' );
	}
	$render = ob_get_clean();
	return $render;
}




