<?php
/**
 * This file belongs to the YIT Framework.
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * @package YITH\PreOrder\Includes\Compatibility
 * @author YITH <plugins@yithemes.com>
 */

if ( ! defined( 'YITH_WCPO_VERSION' ) ) {
	exit( 'Direct access forbidden.' );
}

/**
 * YITH Stripe compatibility class
 *
 * @class      YITH_Pre_Order_YITH_Stripe_Compat
 * @package    Yithemes
 * @since      Version 2.0.0
 */

if ( ! class_exists( 'YITH_Pre_Order_YITH_Stripe_Compat' ) ) {
	/**
	 * Class YITH_Pre_Order_YITH_Stripe_Compat
	 *
	 */
	class YITH_Pre_Order_YITH_Stripe_Compat {

		/**
		 * Main Instance
		 *
		 * @var YITH_Pre_Order_YITH_Stripe_Compat
		 * @since  1.0
		 * @access public
		 */
		protected static $instance;

		/**
		 * Returns single instance of the class
		 *
		 * @return YITH_Pre_Order_YITH_Stripe_Compat
		 * @since 1.0.0
		 */
		public static function get_instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Construct
		 *
		 * @since  2.0
		 */
		public function __construct() {
			if ( 'no' === get_option( 'yith_wcpo_enable_pre_order', 'yes' ) ) {
				return;
			}

			add_filter( 'yith_wcstripe_mode', array( $this, 'force_stripe_elements_mode' ), 10, 2 );
		}

		/**
		 * Force the Stripe Elements payment mode only if the Stripe Checkout mode is selected and there is an upon release pre-order product in the cart.
		 *
		 * @param string                         $mode    The current Stripe payment mode.
		 * @param YITH_WCStripe_Gateway_Advanced $gateway The YITH_WCStripe_Gateway_Advanced instance.
		 *
		 * @return string
		 */
		public function force_stripe_elements_mode( $mode, $gateway ) {
			if ( WC()->cart && ywpo_cart_contains_pre_order_product() && ywpo_is_upon_release_cart() && ( 'hosted_std' === $mode || 'hosted' === $mode ) ) {
				$mode = apply_filters( 'ywpo_force_stripe_payment_mode', 'elements', $mode, $gateway );
			}
			return $mode;
		}
	}
}

/**
 * Unique access to instance of YITH_Pre_Order_YITH_Stripe_Compat
 *
 * @return YITH_Pre_Order_YITH_Stripe_Compat
 */
function YITH_Pre_Order_YITH_Stripe_Compat() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
	return YITH_Pre_Order_YITH_Stripe_Compat::get_instance();
}
