<?php
namespace QuizPressWoocommerce;

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

class Helper {
    
    public static function quizpress_user_has_completed_order( $user_id, $product_id ) {
		if ( ! $user_id || ! $product_id ) {
			return false;
		}

		$orders = wc_get_orders( [
			'customer_id' => $user_id,
			'status'      => 'completed',
			'limit'       => -1,
		] );
			
		if ( empty( $orders ) ) {
			return false;
		}

		foreach ( $orders as $order ) {
			foreach ( $order->get_items() as $item ) {
				if ( intval( $item->get_product_id() ) === intval( $product_id ) ) {
					return true;
				}
			}
		}

		return false;
	}

	public static function quizpress_get_product_purchase_status( $user_id, $product_id ) {
		if ( ! $user_id || ! $product_id ) {
			return false;
		}

		// Get all orders for this user (any status)
		$orders = wc_get_orders( [
			'customer_id' => $user_id,
			'limit'       => -1,
		] );

		if ( empty( $orders ) ) {
			return false; // user has no orders
		}

		foreach ( $orders as $order ) {
			foreach ( $order->get_items() as $item ) {
				if ( intval( $item->get_product_id() ) === intval( $product_id ) ) {
					// Return WooCommerce order status (string)
					return $order->get_status();   // example: completed, processing, pending, failed
				}
			}
		}

		return false; // product not found in any order
	}

	public static function is_product_in_cart( $product_id ) {
		global $woocommerce;
		if ( $woocommerce->cart ) {
			foreach ( $woocommerce->cart->get_cart() as $key => $val ) {
				if ( (int) $product_id === (int) $val['product_id'] ) {
					return true;
				}
			}
		}
		return false;
	}
}