<?php
/**
 * AutoCompleteDigitalOrders class.
 *
 * @package DokanKits\Features\Order
 * @since   3.0.0
 */

namespace DokanKits\Features\Order;

use DokanKits\Features\Feature;
use WC_Product;

/**
 * Auto Complete Virtual Orders Feature
 *
 * Automatically completes orders containing only virtual and downloadable products.
 * This eliminates manual order processing for digital products that require no shipping.
 *
 * @since   3.0.0
 * @package DokanKits\Features\Order
 */
class AutoCompleteDigitalOrders extends Feature {

	/**
	 * Feature option key for enabling/disabling this feature
	 *
	 * @since 3.0.0
	 * @var string
	 */
	protected string $option_key = 'auto_complete_order_checkbox';

	/**
	 * Feature settings group for admin UI organization
	 *
	 * @since 3.0.0
	 * @var string
	 */
	protected string $settings_group = 'shipping';

	/**
	 * Feature settings section within the group
	 *
	 * @since 3.0.0
	 * @var string
	 */
	protected string $settings_section = 'orders';

	/**
	 * Number of sub-features contained in this feature
	 *
	 * @since 3.0.0
	 * @var int
	 */
	protected int $total_features = 1;

	/**
	 * Register hooks with WordPress
	 *
	 * Sets up the filter to automatically complete orders containing
	 * only virtual or downloadable products.
	 *
	 * @since 3.0.0
	 * @return void
	 */
	public function register_hooks(): void {
		add_filter( 'woocommerce_order_item_needs_processing', array( $this, 'auto_complete_virtual_products' ), 10, 2 );
	}

	/**
	 * Auto-complete virtual and downloadable products
	 *
	 * When a product is virtual or downloadable, this filter tells WooCommerce
	 * that the item doesn't need processing, allowing orders to auto-complete.
	 *
	 * @since 3.0.0
	 *
	 * @param bool       $needs_processing Whether the item needs processing.
	 * @param WC_Product $product          Product object.
	 *
	 * @return bool False if the product is virtual/downloadable, original value otherwise.
	 */
	public function auto_complete_virtual_products( bool $needs_processing, WC_Product $product ): bool {
		if ( ! $this->is_enabled() ) {
			return $needs_processing;
		}

		if ( $product->is_virtual() || $product->is_downloadable() ) {
			return false;
		}

		return $needs_processing;
	}
}
