<?php
/**
 * Utils Class
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/utils
 * @author     miniOrange
 * @license    Expat
 * @link       https://miniorange.com
 */

declare( strict_types=1 );

namespace MOMCS_Sync\Includes\Common\Utils;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Utility functions.
 */
class Utils {
	/**
	 * Get plugin version from main file.
	 *
	 * @return string
	 */
	public static function get_plugin_version(): string {
		$file_data      = get_file_data( MOMCS_PLUGIN_DIR . Plugin_Constants::PLUGIN_FILE, array( 'Version' ), 'plugin' );
		$plugin_version = isset( $file_data[0] ) ? $file_data[0] : '1.0.0';
		return $plugin_version;
	}

	/**
	 * Get a unified list of WooCommerce product attributes and useful meta keys for mapping.
	 * Includes core fields, selected meta like Amazon ASIN, taxonomy attributes (pa_),
	 * and a limited set of custom meta keys discovered in the database.
	 *
	 * @return array<string,string> Map of key => human-readable label
	 */
	public static function get_wc_product_attributes(): array {
		// Base WooCommerce fields.
		$attributes = array(
			'post_title'      => esc_html__( 'Product Title', 'multi-channel-for-woocommerce' ),
			'post_content'    => esc_html__( 'Product Description', 'multi-channel-for-woocommerce' ),
			'post_excerpt'    => esc_html__( 'Product Short Description', 'multi-channel-for-woocommerce' ),
			'_thumbnail_id'   => esc_html__( 'Product Thumbnail', 'multi-channel-for-woocommerce' ),
			'_sku'            => esc_html__( 'Product SKU', 'multi-channel-for-woocommerce' ),
			'_momcs_amz_asin' => esc_html__( 'Amazon ASIN', 'multi-channel-for-woocommerce' ),
			'_regular_price'  => esc_html__( 'Regular Price', 'multi-channel-for-woocommerce' ),
			'_sale_price'     => esc_html__( 'Sale Price', 'multi-channel-for-woocommerce' ),
			'_weight'         => esc_html__( 'Weight', 'multi-channel-for-woocommerce' ),
			'_length'         => esc_html__( 'Length', 'multi-channel-for-woocommerce' ),
			'_width'          => esc_html__( 'Width', 'multi-channel-for-woocommerce' ),
			'_height'         => esc_html__( 'Height', 'multi-channel-for-woocommerce' ),
			'_stock'          => esc_html__( 'Stock Quantity', 'multi-channel-for-woocommerce' ),
			'_stock_status'   => esc_html__( 'Stock Status', 'multi-channel-for-woocommerce' ),
			'_visibility'     => esc_html__( 'Visibility', 'multi-channel-for-woocommerce' ),
			'product_cat'     => esc_html__( 'Product Categories', 'multi-channel-for-woocommerce' ),
			'product_tag'     => esc_html__( 'Product Tags', 'multi-channel-for-woocommerce' ),
		);

		// WooCommerce global attributes (pa_*).
		$attribute_taxonomies = function_exists( 'wc_get_attribute_taxonomies' ) ? wc_get_attribute_taxonomies() : array();
		if ( $attribute_taxonomies ) {
			foreach ( $attribute_taxonomies as $tax ) {
				$attributes[ 'pa_' . $tax->attribute_name ] = $tax->attribute_label;
			}
		}

		// Custom meta keys discovered in product posts (exclude leading underscore to avoid internal metas).
		global $wpdb;
		if ( isset( $wpdb ) && property_exists( $wpdb, 'postmeta' ) ) {
			$meta_keys = $wpdb->get_col( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Always need updated data from database.	
				"SELECT DISTINCT meta_key FROM {$wpdb->postmeta} pm
                JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                WHERE p.post_type = 'product'
                AND meta_key NOT LIKE '\\_%'
                LIMIT 100"
			);

			if ( is_array( $meta_keys ) ) {
				foreach ( $meta_keys as $meta_key ) {
					if ( ! isset( $attributes[ $meta_key ] ) ) {
						$attributes[ $meta_key ] = __( 'Custom: ', 'multi-channel-for-woocommerce' ) . $meta_key;
					}
				}
			}
		}

		return $attributes;
	}

	/**
	 * Get the value of a parameter from the current page URL.
	 *
	 * @param string $parameter_name The name of the parameter to get the value of.
	 * @param string $default_value The default value to return if the parameter is not found.
	 * @return string The value of the parameter, or the default value if the parameter is not found.
	 */
	public static function get_current_page_parameter_value( string $parameter_name, string $default_value = '' ): string {
		$path            = home_url( add_query_arg( null, null ) );
		$parameter_value = '';
		$query_str       = wp_parse_url( $path, PHP_URL_QUERY );
		if ( $query_str ) {
			parse_str( $query_str, $query_params );
			if ( ! empty( $query_params[ $parameter_name ] ) ) {
				$parameter_value = $query_params[ $parameter_name ];
			}
			unset( $query_params );
		}
		return ! empty( $parameter_value ) ? $parameter_value : $default_value;
	}

	/**
	 * Check if the current plan is premium.
	 *
	 * @return bool True if premium plan, false otherwise.
	 */
	public static function is_premium_plan(): bool {
		return Plugin_Constants::PLAN_NAME === 'premium' ? true : false;
	}

	/**
	 * Get the limits for the current plan.
	 *
	 * @return array<string,int> The limits for the current plan.
	 */
	public static function get_plan_limits(): array {
		return Plugin_Constants::PLAN_NAME === 'free' ? array(
			'max_templates'          => 1,
			'max_amazon_connections' => 1,
		) : array(
			'max_templates'          => 10,
			'max_amazon_connections' => PHP_INT_MAX,
		);
	}
}
