<?php
/**
 * Standard Product Data Provider
 *
 * Simplified product data extraction for Standard Bulk Generator.
 * Unlike Advanced version: NO custom variables support.
 *
 * @package AIPT\Api\BulkGenerator\Standard\Core
 * @since 2.5.0
 */

namespace AIPT\Api\BulkGenerator\Standard\Core;

/**
 * Product data provider for Standard generator
 */
class StandardProductDataProvider {

	/**
	 * Cache group for transients
	 */
	private const CACHE_GROUP = 'aipt_std_product';

	/**
	 * Cache TTL in seconds (5 minutes)
	 */
	private const CACHE_TTL = 300;

	/**
	 * Get single product data
	 *
	 * @param int  $product_id Product ID.
	 * @param bool $use_cache  Whether to use cache.
	 * @return array|null Product data or null if not found
	 */
	public static function get( int $product_id, bool $use_cache = true ): ?array {
		if ( $use_cache ) {
			$cache_key = self::CACHE_GROUP . '_' . $product_id;
			$cached    = get_transient( $cache_key );
			if ( false !== $cached ) {
				return $cached;
			}
		}

		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			return null;
		}

		$data = self::extractProductData( $product );

		if ( $use_cache ) {
			set_transient( self::CACHE_GROUP . '_' . $product_id, $data, self::CACHE_TTL );
		}

		return $data;
	}

	/**
	 * Bulk get multiple products data
	 *
	 * @param array $product_ids Array of product IDs.
	 * @param bool  $use_cache   Whether to use cache.
	 * @return array Associative array of product_id => data
	 */
	public static function bulkGet( array $product_ids, bool $use_cache = true ): array {
		if ( empty( $product_ids ) ) {
			return array();
		}

		$result      = array();
		$to_load     = array();
		$product_ids = array_unique( array_map( 'absint', $product_ids ) );

		if ( $use_cache ) {
			foreach ( $product_ids as $id ) {
				$cache_key = self::CACHE_GROUP . '_' . $id;
				$cached    = get_transient( $cache_key );
				if ( false !== $cached ) {
					$result[ $id ] = $cached;
				} else {
					$to_load[] = $id;
				}
			}
		} else {
			$to_load = $product_ids;
		}

		if ( ! empty( $to_load ) ) {
			$chunk_size = 100;
			$chunks     = array_chunk( $to_load, $chunk_size );

			foreach ( $chunks as $chunk ) {
				$products = wc_get_products(
					array(
						'include' => $chunk,
						'limit'   => $chunk_size,
						'return'  => 'objects',
					)
				);

				foreach ( $products as $product ) {
					$data                         = self::extractProductData( $product );
					$result[ $product->get_id() ] = $data;

					if ( $use_cache ) {
						$cache_key = self::CACHE_GROUP . '_' . $product->get_id();
						set_transient( $cache_key, $data, self::CACHE_TTL );
					}
				}
			}
		}

		return $result;
	}

	/**
	 * Extract product data for Standard generator
	 *
	 * @param \WC_Product $product WooCommerce product.
	 * @return array Extracted product data
	 */
	private static function extractProductData( \WC_Product $product ): array {
		$raw_price         = $product->get_price();
		$raw_regular_price = $product->get_regular_price();
		$raw_sale_price    = $product->is_on_sale() ? $product->get_sale_price() : '';

		$data = array(
			'id'                    => $product->get_id(),
			'name'                  => $product->get_name(),
			'sku'                   => $product->get_sku() ?: '',
			'price'                 => ( $raw_price !== '' && $raw_price !== null ) ? (string) $raw_price : '',
			'regular_price'         => ( $raw_regular_price !== '' && $raw_regular_price !== null ) ? (string) $raw_regular_price : '',
			'sale_price'            => ( $raw_sale_price !== '' && $raw_sale_price !== null ) ? (string) $raw_sale_price : '',
			'price_display'         => ( $raw_price !== '' && $raw_price !== null ) ? wp_strip_all_tags( wc_price( $raw_price ) ) : '',
			'regular_price_display' => ( $raw_regular_price !== '' && $raw_regular_price !== null ) ? wp_strip_all_tags( wc_price( $raw_regular_price ) ) : '',
			'sale_price_display'    => ( $raw_sale_price !== '' && $raw_sale_price !== null ) ? wp_strip_all_tags( wc_price( $raw_sale_price ) ) : '',
			'categories'            => self::extractCategories( $product ),
			'categories_string'     => '',
			'attributes'            => self::extractAttributes( $product ),
			'formatted_attributes'  => '',
			'short_description'     => $product->get_short_description(),
			'description'           => $product->get_description(),
			'tags'                  => self::extractTags( $product ),
			'tags_string'           => '',
		);

		$data['categories_string'] = implode( ', ', $data['categories'] );
		$data['tags_string']       = implode( ', ', $data['tags'] );

		$attr_texts = array();
		foreach ( $data['attributes'] as $name => $value ) {
			$attr_texts[] = $name . ': ' . $value;
		}
		$data['formatted_attributes'] = implode( ' | ', $attr_texts );

		return $data;
	}

	/**
	 * Extract product categories
	 *
	 * @param \WC_Product $product WooCommerce product.
	 * @return array Array of category names
	 */
	private static function extractCategories( \WC_Product $product ): array {
		$terms = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'names' ) );
		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return array();
		}
		return array_map(
			function ( $cat ) {
				return html_entity_decode( $cat, ENT_QUOTES, 'UTF-8' );
			},
			$terms
		);
	}

	/**
	 * Extract product tags
	 *
	 * @param \WC_Product $product WooCommerce product.
	 * @return array Array of tag names
	 */
	private static function extractTags( \WC_Product $product ): array {
		$terms = wp_get_post_terms( $product->get_id(), 'product_tag', array( 'fields' => 'names' ) );
		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return array();
		}
		return $terms;
	}

	/**
	 * Extract product attributes
	 *
	 * @param \WC_Product $product WooCommerce product.
	 * @return array Associative array of attribute_name => values
	 */
	private static function extractAttributes( \WC_Product $product ): array {
		$result     = array();
		$attributes = $product->get_attributes();

		if ( empty( $attributes ) ) {
			return $result;
		}

		foreach ( $attributes as $attribute ) {
			if ( ! $attribute->get_visible() ) {
				continue;
			}

			$name   = wc_attribute_label( $attribute->get_name() );
			$values = array();

			if ( $attribute->is_taxonomy() ) {
				$terms = wp_get_post_terms( $product->get_id(), $attribute->get_name(), array( 'fields' => 'names' ) );
				if ( ! is_wp_error( $terms ) ) {
					$values = $terms;
				}
			} else {
				$values = $attribute->get_options();
			}

			if ( ! empty( $values ) ) {
				$result[ $name ] = implode( ', ', $values );
			}
		}

		return $result;
	}

	/**
	 * Clear cache for a specific product
	 *
	 * @param int $product_id Product ID.
	 * @return void
	 */
	public static function clearCache( int $product_id ): void {
		delete_transient( self::CACHE_GROUP . '_' . $product_id );
	}

	/**
	 * Clear all Standard generator product caches
	 *
	 * @return void
	 */
	public static function clearAllCache(): void {
		global $wpdb;

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
				'_transient_' . self::CACHE_GROUP . '_%'
			)
		);

	}
}
