<?php
/**
 * Buy Now extension — redirect engine.
 *
 * Single-product-form path only: the Buy Now button submits the native
 * add-to-cart form carrying a `brandy_buy_now` flag; after WooCommerce adds the
 * product (validating variation + quantity), the post-add flow is redirected to
 * checkout via `woocommerce_add_to_cart_redirect`, optionally clearing the rest
 * of the cart for an express single-item purchase.
 *
 * @package Brandy\WooCommerce\BuyNow
 */

namespace Brandy\WooCommerce\BuyNow;

defined( 'ABSPATH' ) || exit;

class RedirectEngine {

	/**
	 * Cart item key added during a Buy Now submit. Captured so empty-cart mode
	 * never removes the item we just added. Request-scoped.
	 *
	 * @var string
	 */
	private static $buy_now_cart_key = '';

	/**
	 * Remember the cart key of the item this Buy Now submit just added, so
	 * empty-cart mode can remove only the others.
	 *
	 * @param string $cart_item_key Key WooCommerce assigned to the added item.
	 */
	public static function capture_cart_key( $cart_item_key ) {
		if ( ! empty( $_REQUEST['brandy_buy_now'] ) ) {
			self::$buy_now_cart_key = (string) $cart_item_key;
		}
	}

	/**
	 * When the submit carried `brandy_buy_now`, optionally clear other cart
	 * items and redirect to checkout.
	 *
	 * @param string $url Default post-add redirect URL.
	 * @return string
	 */
	public static function filter_add_to_cart_redirect( $url ) {
		if ( empty( $_REQUEST['brandy_buy_now'] ) || ! is_wc_installed() ) {
			return $url;
		}

		if ( Settings::empty_cart() ) {
			self::empty_cart_except_buy_now_item();
		}

		return wc_get_checkout_url();
	}

	/**
	 * Remove every cart item except the one just added by this Buy Now submit.
	 * If the key was not captured, do nothing rather than risk emptying the
	 * item we intend to buy.
	 */
	private static function empty_cart_except_buy_now_item() {
		if ( ! WC()->cart || '' === self::$buy_now_cart_key ) {
			return;
		}

		foreach ( array_keys( WC()->cart->get_cart() ) as $cart_item_key ) {
			if ( $cart_item_key !== self::$buy_now_cart_key ) {
				WC()->cart->remove_cart_item( $cart_item_key );
			}
		}
	}
}
