<?php
namespace Pay4All\Pro\Integrations\Age;

use Pay4All\Age\Services\Kyc;

if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * WooCommerce-cart reader for the age-verification gate.
 *
 * Lives here (and not in pay4all-age) so the free plugin stays free
 * of any WooCommerce runtime code. The method only makes sense on a
 * site running WooCommerce, and it's only called from the Pro-side
 * `Checkout` integration — moving it out of pay4all-age keeps the
 * free plugin's readme claim (« does not ship any merchant-facing
 * WooCommerce surfaces ») literally true.
 */
final class WooCart {

	/**
	 * True when the current cart contains at least one age-restricted
	 * product AND the logged-in customer isn't already verified from a
	 * previous purchase.
	 */
	public static function cart_needs_kyc() : bool {
		if ( ! function_exists( 'WC' ) || ! WC()->cart ) { return false; }
		// Verified logged-in customer : reuse their previously uploaded
		// photos, skip the whole capture UI. The order still gets an
		// audit trail via the `_pay4all_age_verified_from_user` meta
		// written by `migrate_session_to_order`.
		if ( is_user_logged_in() && Kyc::is_user_verified( get_current_user_id() ) ) {
			return false;
		}
		foreach ( WC()->cart->get_cart() as $item ) {
			$product_id = 0;
			if ( is_object( $item['data'] ?? null ) && method_exists( $item['data'], 'get_id' ) ) {
				$product_id = (int) $item['data']->get_id();
			}
			if ( ! $product_id ) { $product_id = (int) ( $item['product_id'] ?? 0 ); }
			if ( Kyc::is_product_age_required( $product_id ) ) { return true; }
		}
		return false;
	}
}
