<?php
namespace ARCHM\Helpers;

/**
 * Universal Membership Helper Class
 * Detects membership products and orders across membership plugins
 *
 * Supports:
 * - "Membership for WooCommerce" (WPSwings) by checking product meta
 *   that links a membership plan to a product.
 * - "WooCommerce Memberships" by checking order meta "_wc_memberships_access_granted"
 *   and plan->product associations.
 *
 * @since 1.7.1
 * @package ArchiveMaster
 */
class MembershipHelper {

    /**
     * Static cache of membership plans to avoid repeated lookups
     *
     * @var array|null
     */
    private static $cached_plans = null;

    /**
     * Get membership plans with caching
     *
     * @return array Array of WC_Memberships_Membership_Plan objects or empty array if none/not available
     */
    private static function get_cached_membership_plans() {
        if ( ! function_exists('wc_memberships_get_membership_plans') ) {
            return [];
        }

        if ( null === self::$cached_plans ) {
            self::$cached_plans = wc_memberships_get_membership_plans();
        }

        return ( self::$cached_plans ) ? self::$cached_plans : [];
    }

	/**
	 * Check if a product is a membership product
	 *
	 * Strategy:
	 * - Look for known meta keys used to attach a membership plan to a product
	 *   (e.g., 'wps_membership_plan_with_product' from WPSwings Membership for WooCommerce)
	 * - Also check parent for variations
	 *
	 * @param int|\WC_Product $product
	 * @return bool
	 */
	public static function is_membership_product( $product ) {
		if ( is_numeric($product) ) {
			$product = wc_get_product($product);
		}

		if ( ! $product || ! ( $product instanceof \WC_Product ) ) {
			return false;
		}

		// Known meta keys for membership linkage
		$known_membership_meta_keys = [
			// WPSwings Membership for WooCommerce: plan attached to product
			'wps_membership_plan_with_product',
		];

		foreach ( $known_membership_meta_keys as $meta_key ) {
			$value = $product->get_meta($meta_key, true);
			if ( ! empty($value) ) {
				return true;
			}
		}

		// If this is a variation, check the parent product as well
		if ( $product->is_type('variation') ) {
			$parent_id = $product->get_parent_id();
			if ( $parent_id ) {
				$parent = wc_get_product($parent_id);
				if ( $parent instanceof \WC_Product ) {
					foreach ( $known_membership_meta_keys as $meta_key ) {
						$value = $parent->get_meta($meta_key, true);
						if ( ! empty($value) ) {
							return true;
						}
					}
				}
			}
		}

		// WooCommerce Memberships: check plan associations by product id
		if ( class_exists('\WC_Memberships_Membership_Plan') ) {
			$product_id = (int) $product->get_id();
			$parent_id  = $product->is_type('variation') ? (int) $product->get_parent_id() : 0;

			foreach ( self::get_cached_membership_plans() as $plan ) {
				// Check the product itself
				if ( $plan->has_product($product_id) ) {
					return true;
				}
				// For variations, check parent
				if ( $parent_id && $plan->has_product($parent_id) ) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Check if an order contains a membership product
	 *
	 * @param \WC_Order $order
	 * @return bool
	 */
	public static function is_membership_order( $order ) {
		if ( ! $order || ! ( $order instanceof \WC_Order ) ) {
			return false;
		}

		// Preferred: WooCommerce Memberships explicit order marker
		if ( function_exists('wc_memberships_get_order_access_granted_memberships') ) {
			$granted = wc_memberships_get_order_access_granted_memberships($order);
			if ( is_array($granted) && ! empty($granted) ) {
				return true;
			}
		} else {
			// Fallback: direct meta read if function unavailable
			$meta = $order->get_meta('_wc_memberships_access_granted', true);
			if ( is_array($meta) && ! empty($meta) ) {
				return true;
			}
		}

		// Secondary: product-level detection (WPSwings + Woo Memberships plan associations)
		foreach ( $order->get_items() as $item ) {
			if ( ! ( $item instanceof \WC_Order_Item_Product ) ) {
				continue;
			}

			$product = $item->get_product();
			if ( $product && self::is_membership_product($product) ) {
				return true;
			}
		}

		return false;
	}
}
