<?php
/**
 * Product helper functions.
 *
 * @package SAAI\Helpers
 * @since 1.0.2
 */

namespace SAAI\Helpers;

/**
 * Product helper class.
 *
 * @since 1.0.2
 */
class Product {

    /**
     * Construct product info
     *
     * @param int $product_id Product ID to construct product info for.
     *
     * @since 1.0.2
     * @return array
     */
    public static function get_product_info( $product_id ) {
        $product = wc_get_product( $product_id );

        if ( ! $product ) {
            return new \WP_Error( 'invalid_product_id', __( 'Invalid product ID.', 'storeagent-ai-for-woocommerce' ), array( 'status' => 400 ) );
        }

        $product_info = $product->get_data();

        return apply_filters( 'saai_product_info', $product_info, $product_id );
    }

    /**
     * Get the total products with meta key count.
     *
     * @param string $meta_key The meta key to check.
     *
     * @since 1.0.5
     * @return int The total products with meta key count.
     */
    public static function get_total_products_with_meta_key_count( $meta_key ) {
        $args = array(
            'post_type'    => 'product',
            'meta_key'     => $meta_key,
            'meta_compare' => 'EXISTS',
            'fields'       => 'ids',
        );

        $query = new \WP_Query( $args );

        return $query->found_posts;
    }

    /**
     * Get the total categories with meta key count.
     *
     * @param string $meta_key The meta key to check.
     *
     * @since 1.0.5
     * @return int The total categories with meta key count.
     */
    public static function get_total_categories_with_meta_key_count( $meta_key ) {
        $args = array(
            'taxonomy'     => 'product_cat',
            'meta_key'     => $meta_key,
            'meta_compare' => 'EXISTS',
            'fields'       => 'ids',
        );

        $query = new \WP_Term_Query( $args );

        return count( $query->get_terms() );
    }
}
