<?php

namespace Bright_Deposits_For_WooCommerce\Pages;

use Bright_Deposits_For_WooCommerce\Helpers\Helper;
use Bright_Deposits_For_WooCommerce\Core\ContainerManager;

/**
 * @package Bright_Deposits_For_WooCommerce\Pages
 * @since 1.0.0
 * @author Bright Plugins
 * Description: This class is responsible for handling the product page functionalities for deposits in WooCommerce.
 */
class Product {

	/**
	 * Singleton instance of the class.
	 * @since 1.0.0
	 * @var Product
	 */
	private static $instance = null;

	protected $helper, $exclusion_manager;

	/**
	 * @since 1.0.0
	 * @var array
	 */
	public $exclude_global_products;

	public function __construct() {
		
		$this->helper = ContainerManager::get('helper');
		$this->exclusion_manager = ContainerManager::get('exclusion_manager');

		add_action( 'woocommerce_before_add_to_cart_button', [$this, 'before_add_to_cart'], 10 );
		add_action( 'woocommerce_product_data_tabs', [$this, 'productTab'] );
		add_action( 'woocommerce_product_data_panels', [$this, 'optionsFileds'] );
		add_action( 'woocommerce_process_product_meta', [$this, 'saveProductMetaData'] );
		add_filter( 'woocommerce_add_to_cart_validation', [$this, 'validateFrontendInput'], 10, 3 );

		if ( $this->helper->getOptionValue( 'variable_product_mode' ) == 'child' ) {
			add_action( 'woocommerce_product_after_variable_attributes', [$this, 'variationsFields'], 10, 3 );
			add_action( 'woocommerce_save_product_variation', [$this, 'variationsFieldsSave'], 10, 2 );
		}

		if ( $this->helper->getOptionValue( 'global_deposits_mode' ) == 1 ) {
			add_filter( 'global_product_type_deposit', '__return_true' );
		}
	}

	/**
	 * Get the singleton instance of the class.
	 * @since 1.0.0
	 * @return Product
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Prevents cloning of the instance.
	 * @since 1.0.0
	 */
	private function __clone() {
		// Cloning is forbidden.
	}

	/**
	 * Prevents unserializing of the instance.
	 * @since 1.0.0
	 */
	public function __wakeup() {
		// Unserializing instances of this class is forbidden.
	}

	/**
	 * Validate deposit input
	 * @since 1.0.0
	 * @param  [boolen] $passed
	 * @param  [int]    $product_id
	 * @param  [int]    $quantity
	 * @return boolen
	 */
	public function validateFrontendInput( $passed, $product_id, $quantity ) {

		$product = wc_get_product( $product_id );
		if ( ! $product instanceof \WC_Product ) {
			return $passed;
		}

		// Check if deposit-related data is being submitted
		$deposit_mode = ( isset( $_POST['deposit-mode'] ) ) ? sanitize_text_field( wp_unslash( $_POST['deposit-mode'] ) ) : '';
		$has_deposit_data = !empty( $deposit_mode ) || isset( $_POST['bdfwbp_add_to_cart_button_nonce'] );

		/**
		 * Nonce verification for add to cart button
		 * If deposit-related data is present, nonce validation is REQUIRED to prevent CSRF
		 */
		if ( $has_deposit_data ) {
			if ( ! isset( $_POST['bdfwbp_add_to_cart_button_nonce'] ) ) {
				wc_add_notice( esc_html__( 'Security check failed. Please refresh the page and try again.', 'bright-deposits-for-woocommerce' ), 'error' );
				return false;
			}

			$nonce = sanitize_text_field( wp_unslash( $_POST['bdfwbp_add_to_cart_button_nonce'] ) );
			if ( ! wp_verify_nonce( $nonce, 'bdfwbp_add_to_cart_button' ) ) {
				wc_add_notice( esc_html__( 'Security check failed. Please refresh the page and try again.', 'bright-deposits-for-woocommerce' ), 'error' );
				return false;
			}
		}

		if ( !WC()->cart->is_empty() && $this->helper->cartHaveDepositItem() && $this->helper->getOptionValue( 'select_mode' ) != 'allow_mix' ) {

			if ( !empty( $deposit_mode ) && $deposit_mode == 'check_deposit' ) {
				return $passed;
			}

			if ( empty( $deposit_mode ) && $this->helper->getOptionValue( 'predefine_full_payment' ) == 0 ) {
				return $passed;
			}	

			$deposit_notice = $this->helper->getOptionValue( 'deposit_notice' );

			wc_add_notice( wp_kses_post( $deposit_notice ), 'error' );

			return false;
		}

		if ( !WC()->cart->is_empty() && $this->helper->cartHaveDepositItem() == false && $this->helper->getOptionValue( 'select_mode' ) != 'allow_mix' ) {

			if ( !empty( $deposit_mode ) && $deposit_mode == 'check_full' ) {
				return $passed;
			} 
			
			if ( empty( $deposit_mode ) && $this->helper->getOptionValue( 'predefine_full_payment' ) == 1 ) {
				return $passed;
			}

			$regular_notice = $this->helper->getOptionValue( 'regular_notice' );

			wc_add_notice( wp_kses_post( $regular_notice ), 'error' );

			return false;
		}

		$is_product_deposit_forced = $product->get_meta( '_bdfwbp_force_deposit_checked', true );

		if ( $is_product_deposit_forced == 'yes' && !empty( $deposit_mode ) && $deposit_mode != 'check_deposit' ) {
			wc_add_notice( wp_kses_post( $this->helper->getOptionValue( 'bdfw_full_payment_not_allowed_label' ) ), 'error' );
			return false;
		}

		return $passed;
	}

	/**
	 * Add elements before add to cart form on the single product page
	 * @since 1.0.0
	 * @return void
	 */
	public function before_add_to_cart() {
		
	/**
	 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before adding the deposit fields to the single product page.
	 * @since 1.0.0
	 * @return void
	 */
	do_action( 'bdfwbp_before_add_to_cart_button' );

	// Get the current product ID
	$current_product_id = get_the_ID();
	$product = wc_get_product( $current_product_id );
	
	// For variable products in 'child' mode, JavaScript will handle variation-specific deposit info via AJAX
	// This method only renders the initial form structure
	$target_product_id = $current_product_id;

		if ( $this->exclusion_manager->is_product_excluded( $product ) ) {
			return;
		}
		
		if ( $this->helper->isProductTypeDeposit( get_the_ID() ) ) {

			// Use the common method to calculate deposit data
			$deposit_data = $this->calculateDepositData( $target_product_id );
			if ( ! $deposit_data ) {
				return;
			}

			$deposit_amount = $deposit_data['deposit_amount'];
			$deposit_text = $deposit_data['deposit_text'];
			$is_deposit_forced = $deposit_data['is_deposit_forced'];

		// --- Start of radio button default selection logic ---
		$predefine_full = $this->helper->getOptionValue('predefine_full_payment') == 1;
		
		// Determine default radio button selection based on plugin settings
		$check_deposit_option = false;
		$check_full_option = false;
		
		if ($is_deposit_forced) {
			// If deposit is forced, only allow deposit option
			$check_deposit_option = true;
		} else {
			// If not forced, use global preference
			if ($predefine_full) {
				$check_full_option = true;  // Default to full payment
			} else {
				$check_deposit_option = true;  // Default to deposit
			}
		}
		// --- End of radio button logic ---

			?>
            <div class="deposits-frontend-wrapper">
			
			<?php wp_nonce_field( 'bdfwbp_add_to_cart_button', 'bdfwbp_add_to_cart_button_nonce' ); ?>
           
			<p class="deposit-notice"><?php echo wp_kses_post($deposit_text); ?></p>
			<div class="deposits-input-wrapper">
				<?php if ( $this->helper->getOptionValue( 'global_hide_deposit_input' ) != 1 ) {

					if ( ! $is_deposit_forced ) { ?>

						<div>
							<input type="radio" name="deposit-mode" value="check_full" <?php if ( $check_full_option ) { echo 'checked'; } ?>>
							<label><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_full_payment_label' ) ); ?></label>
						</div>

						<div>
							<input type="radio" name="deposit-mode" value="check_deposit" <?php if ( $check_deposit_option ) { echo 'checked'; } ?>>
							<label><?php echo esc_html( $this->helper->getOptionValue( 'bdfw_pay_deposit_label' ) ); ?></label>
						</div>

				<?php }

				} else {
					echo '<input type="hidden" name="deposit-mode" value="check_deposit">';
				}?>

            </div>
			<?php
			$deposit_custom_text = $this->helper->getOptionValue('bdfw_deposit_notice_custom_text');
			if ( ! empty( $deposit_custom_text ) ) {
				?>
				<div id="bdfw-deposit-notice-custom-text" class="bdfw-deposit-notice-custom-text" style="border: 1px solid #000; padding: 20px; margin-top: 10px; <?php if ( ! $check_deposit_option ) { echo 'display:none;'; } ?>">
					<?php echo wp_kses_post( $this->replacePlaceholders( $deposit_custom_text, $product->get_id() ) ); ?>
				</div>
				<?php
			}
			?>

            <span style="margin-bottom:15px;display: block;"></span>
            </div>


        <?php }

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after adding the deposit fields to the single product page.
		 * @since 1.0.0
		 * @return void
		 */
		do_action( 'bdfwbp_after_add_to_cart_button' );
	}
	
	/**
	 * Saves WooCommerce Product deposits custom fields woo_desposits_options
	 * @since 1.0.0
	 * @param int $post_id
	 * @return void
	 */
	public function saveProductMetaData( $post_id ) {

		/**
		 * Nonce verification for product meta data
		 * Here we use the WooCommerce nonce because we are in a WooCommerce metabox.
		 * For other cases, you should use the standard nonce "_wpnonce".
		 */
		if( !isset( $_POST['woocommerce_meta_nonce'] ) ){
			wp_die( esc_html__( 'Not found nonce.', 'bright-deposits-for-woocommerce' ) );
		}

		$nonce = sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) );
		$action = 'woocommerce_save_data';

		if ( !wp_verify_nonce( $nonce, $action ) ) {
			wp_die( esc_html__( 'Security check failed. Please try again.', 'bright-deposits-for-woocommerce' ) );
		}
		/**
		 * End of nonce verification for product meta data
		 */
		
		$product = wc_get_product( $post_id );
		if ( ! $product instanceof \WC_Product ) {
			return;
		}

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before saving the deposit fields of product.
		 * @since 1.0.0
		 * @param \WC_Product $product
		 * @return void
		 */
		do_action( 'bdfwbp_before_save_product_meta_data', $product );

		$field_enable_deposit = isset( $_POST['_bdfwbp_enable_deposit'] ) ? sanitize_text_field( wp_unslash( $_POST['_bdfwbp_enable_deposit'] ) ) : 'no';
		$variationDeposit     = isset( $_POST['_bdfwbp_enable_variation_deposit'] ) ? sanitize_text_field( wp_unslash( $_POST['_bdfwbp_enable_variation_deposit'] ) ) : 'no';
		$field_force_deposit  = isset( $_POST['_bdfwbp_force_deposit_checked'] ) ? sanitize_text_field( wp_unslash( $_POST['_bdfwbp_force_deposit_checked'] ) ) : 'no';
		$field_deposits_type  = isset( $_POST['_bdfwbp_deposits_type'] ) ? sanitize_text_field( wp_unslash( $_POST['_bdfwbp_deposits_type'] ) ) : '';
		$field_deposits_value = isset( $_POST['_bdfwbp_deposits_value'] ) ? sanitize_text_field( wp_unslash( $_POST['_bdfwbp_deposits_value'] ) ) : '';

		$product->update_meta_data( '_bdfwbp_enable_deposit', $field_enable_deposit );
		$product->update_meta_data( '_bdfwbp_enable_variation_deposit', $variationDeposit );

		if ( !empty( $field_force_deposit ) ) {
			$product->update_meta_data( '_bdfwbp_force_deposit_checked', $field_force_deposit );
		}

		if ( !empty( $field_deposits_type ) ) {
			$product->update_meta_data( '_bdfwbp_deposits_type', $field_deposits_type );
		}

		if ( !empty( $field_deposits_value ) ) {
			$product->update_meta_data( '_bdfwbp_deposits_value', intval( $field_deposits_value ) );
		}
		

		$product->save();
	}

	/**
	 * Add a deposit custom tab in product page admin.
	 * @since 1.0.0
	 * @param  array   $tabs
	 * @return mixed
	 */
	public function productTab( $tabs ) {
		$tabs['deposits'] = array(
			'label'  => __( 'Deposit', 'bright-deposits-for-woocommerce' ),
			'target' => 'woo_desposits_options',
			'class'  => array( 'show_if_simple', 'show_if_variable' ),
		);

		return $tabs;
	}

	/**
	 *  Add deposit fields to product page admin.
	 * @since 1.0.0
	 * @return void
	 */
	public function optionsFileds() {
		?>
        <div id="woo_desposits_options" class="panel woocommerce_options_panel">
        <div class="options_group <?php echo ( $this->helper->getOptionValue( 'variable_product_mode' ) == 'child' ) ? esc_attr( 'deposit-variation-option' ) : ''; ?>" style="display:none">
        <?php woocommerce_wp_checkbox(
			array(
				'id'          => '_bdfwbp_enable_variation_deposit',
				'label'       => __( 'Enable Deposit', 'bright-deposits-for-woocommerce' ),
				'value'       => get_post_meta( get_the_ID(), '_bdfwbp_enable_variation_deposit', true ),
				'description' => __( 'Enable deposit feature for this Variable product.', 'bright-deposits-for-woocommerce' ),
			)
		);

		?>
        </div>
        <div class="options_group">
        <?php
		
		if ( $this->helper->getOptionValue( 'variable_product_mode' ) == 'child' && wc_get_product(get_the_ID())->get_type() == 'variable' ) {
			return;
		}
		woocommerce_wp_checkbox(
			array(
				'id'          => '_bdfwbp_enable_deposit',
				'label'       => __( 'Enable Deposit', 'bright-deposits-for-woocommerce' ),
				'value'       => get_post_meta( get_the_ID(), '_bdfwbp_enable_deposit', true ),
				'description' => __( 'Enable deposits feature for this product.', 'bright-deposits-for-woocommerce' ),
			)
		);
		woocommerce_wp_checkbox(
			array(
				'id'          => '_bdfwbp_force_deposit_checked',
				'label'       => __( 'Force Deposit', 'bright-deposits-for-woocommerce' ),
				'placeholder' => '',
				'value'       => get_post_meta( get_the_ID(), '_bdfwbp_force_deposit_checked', true ),
				'description' => __( 'Only deposit payment is allow for this product.', 'bright-deposits-for-woocommerce' ),
			)
		);

		// Type.
		woocommerce_wp_select(
			array(
				'id'      => '_bdfwbp_deposits_type',
				'label'   => __( 'Deposit type', 'bright-deposits-for-woocommerce' ),
				'class'   => 'wc-enhanced-select',
				'options' => [
					'percentage'   => __( 'Percentage of Amount', 'bright-deposits-for-woocommerce' ),
					'fixed_amount' => __( 'Fixed Amount', 'bright-deposits-for-woocommerce' ),
				],
				'value'   => get_post_meta( get_the_ID(), '_bdfwbp_deposits_type', true ),
			)
		);
		woocommerce_wp_text_input(
			array(
				'id'          => '_bdfwbp_deposits_value',
				'label'       => __( 'Deposit Value *', 'bright-deposits-for-woocommerce' ),
				'placeholder' => '',
				'value'       => get_post_meta( get_the_ID(), '_bdfwbp_deposits_value', true ),
				'style'       => 'width:60px;',
				'description' => __( 'Enter the value for deposit. only number allow.', 'bright-deposits-for-woocommerce' ),
			)
		);

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add aonther item after added the last deposit field to product.
		 * @since 1.0.0
		 * @return void
		 */
		do_action( 'bdfwbp_after_options_product_fields' );

		?>
 		</div>
        </div>
    	<?php
	}

	/**
	 * Add deposit fields to variable products
	 * @since 1.0.0
	 * @param int $loop
	 * @param array $variation_data
	 * @param \WC_Product_Variation $variation
	 * @return void
	 */
	public function variationsFields( $loop, $variation_data, $variation ) {

		echo '<div class="bdfwbp-variable-options options_group woocommerce_options_panel form-row form-row-full ">';

		woocommerce_wp_checkbox(
			array(
				'id'          => '_bdfwbp_enable_deposit' . $variation->ID,
				'label'       => __( 'Enable Deposit', 'bright-deposits-for-woocommerce' ),
				'value'       => get_post_meta( $variation->ID, '_bdfwbp_enable_deposit', true ),
				'description' => __( 'Enable deposits feature for this product.', 'bright-deposits-for-woocommerce' ),
			)
		);

		woocommerce_wp_checkbox(
			array(
				'id'          => '_bdfwbp_force_deposit_checked' . $variation->ID,
				'label'       => __( 'Force Deposit', 'bright-deposits-for-woocommerce' ),
				'placeholder' => '',
				'value'       => get_post_meta( $variation->ID, '_bdfwbp_force_deposit_checked', true ),
				'description' => __( 'Only deposit payment is allow for this product.', 'bright-deposits-for-woocommerce' ),
			)
		);

		woocommerce_wp_select(
			array(
				'id'      => '_bdfwbp_deposits_type' . $variation->ID,
				'label'   => __( 'Deposit type', 'bright-deposits-for-woocommerce' ),
				'class'   => 'wc-enhanced-select',
				'options' => [
					'percentage' => __( 'Percentage of Amount', 'bright-deposits-for-woocommerce' ),
					'fixed_amount'   => __( 'Fixed Amount', 'bright-deposits-for-woocommerce' ),
				],
				'value'   => get_post_meta( $variation->ID, '_bdfwbp_deposits_type', true ),
			)
		);

		woocommerce_wp_text_input(
			array(
				'id'          => '_bdfwbp_deposits_value' . $variation->ID,
				'label'       => __( 'Deposit Value *', 'bright-deposits-for-woocommerce' ),
				'placeholder' => '',
				'value'       => get_post_meta( $variation->ID, '_bdfwbp_deposits_value', true ),
				'style'       => 'width:60px;',
				'description' => __( 'Enter the value for deposit. only number allow.', 'bright-deposits-for-woocommerce' ),
			)
		);

		// Nonce for saving the product variation
		wp_nonce_field( 'save_product_variation_' . $variation->ID, 'save_product_variation_nonce_' . $variation->ID );

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add aonther item after added the last deposit field to variable products.
		 * @since 1.0.0
		 * @param int $loop
		 * @param array $variation_data
		 * @param \WC_Product_Variation $variation
		 * @return void
		 */
		do_action( 'bdfwbp_after_variations_fields', $loop, $variation_data, $variation );

		echo '</div>';
	}

	/**
	 * Save deposit fields of product.
	 * @since 1.0.0
	 * @param int $variation_id
	 * @return void
	 */
	public function variationsFieldsSave( $variation_id ) {

		/**
		 * Nonce verification for product variation
		 * Here we use the custom nonce and action for product variation. Not exist a standard nonce and action for product variation.
		 * For other cases, you should use the standard nonce "_wpnonce".
		 */
		if( !isset( $_POST['save_product_variation_nonce_' . $variation_id] ) ){
			wp_die( esc_html__( 'Not found nonce.', 'bright-deposits-for-woocommerce' ) );
		}

		$nonce = sanitize_text_field( wp_unslash( $_POST['save_product_variation_nonce_' . $variation_id] ) );
		$action = 'save_product_variation_' . $variation_id;

		if ( !wp_verify_nonce( $nonce, $action ) ) {
			wp_die( esc_html__( 'Security check failed. Please try again.', 'bright-deposits-for-woocommerce' ) );
		}
		/**
		 * End of nonce verification for product variation
		 */

		$product = wc_get_product( $variation_id );
		if ( ! $product instanceof \WC_Product ) {
			return;
		}

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code before saving the deposit fields of variable product.
		 * @since 1.0.0
		 * @param \WC_Product $product
		 * @return void
		 */
		do_action( 'bdfwbp_before_variations_fields_save', $product );

		$post_data = $_POST;

		$enableDeposit = $this->get_sanitized_product_variant_post_value( $product->get_id(), '_bdfwbp_enable_deposit', 'no', $post_data );
		$forceDeposit  = $this->get_sanitized_product_variant_post_value( $product->get_id(), '_bdfwbp_force_deposit_checked', 'no', $post_data );
		$depositType   =  $this->get_sanitized_product_variant_post_value( $product->get_id(), '_bdfwbp_deposits_type', '', $post_data );
		$initial_payment_total  = $this->get_sanitized_product_variant_post_value( $product->get_id(), '_bdfwbp_deposits_value', '', $post_data );

		$product->update_meta_data( '_bdfwbp_enable_deposit', $enableDeposit );
		$product->update_meta_data( '_bdfwbp_force_deposit_checked', $forceDeposit );
		$product->update_meta_data( '_bdfwbp_deposits_type', $depositType );
		$product->update_meta_data( '_bdfwbp_deposits_value', $initial_payment_total );

		$product->save();

		/**
		 * BDFWBP_CUSTOM_ACTION_HOOK: Allows developers to add code after saving the deposit fields of variable product.
		 * @since 1.0.0
		 * @param \WC_Product $product
		 * @return void
		 */
		do_action( 'bdfwbp_after_variations_fields_save', $product );
	}

	/**
	 * Get a safe value from the $_POST array for a specific product.
	 *
	 * @param int    $product_id   The ID of the product.
	 * @param string $key_suffix   The suffix of the key in $_POST (ej: '_bdfwbp_enable_deposit').
	 * @param mixed  $default      The value to return if the key does not exist.
	 * @return string              The sanitized value or the default value.
	 */
	public function get_sanitized_product_variant_post_value( $product_id, $key_suffix, $default = '', $post_data = array() ) {
		// 1. Build the complete key for the $_POST array.
		$post_key = $key_suffix . $product_id;

		// 2. Get the value using isset() before sanitizing.
		$value = isset( $post_data[$post_key] ) ? sanitize_text_field( wp_unslash( $post_data[$post_key] ) ) : $default;

		// 3. Return the sanitized value.
		return $value;
	}

	/**
	 * Calculate deposit data for a given product/variation ID
	 * @since 1.0.0
	 * @param int $product_id The product or variation ID
	 * @return array Array containing deposit data
	 */
	public function calculateDepositData( $product_id ) {
		$product = wc_get_product( $product_id );
		if ( ! $product instanceof \WC_Product ) {
			return null;
		}

		$product_deposit_value  = get_post_meta( $product_id, '_bdfwbp_deposits_value', true );
		$product_deposit_type   = get_post_meta( $product_id, '_bdfwbp_deposits_type', true );
		$product_enable_deposit = ( get_post_meta( $product_id, '_bdfwbp_enable_deposit', true ) == 'yes' ) ? true : false;
		$product_force_deposit  = ( get_post_meta( $product_id, '_bdfwbp_force_deposit_checked', true ) == 'yes' ) ? true : $this->helper->getOptionValue('global_force_deposit');	

		$deposit_type = ( $product_enable_deposit ) ? $product_deposit_type : $this->helper->getOptionValue('global_deposit_type');
		
		if ($deposit_type === 'percentage') {
			$deposit_value = $product_enable_deposit ? $product_deposit_value : $this->helper->getOptionValue('global_deposit_percentage');
			$deposit_amount = ( $deposit_value / 100 ) * $product->get_price();
		} else {
			$deposit_value = $product_enable_deposit ? $product_deposit_value : $this->helper->getOptionValue('global_deposit_fixed_amount');
			$deposit_amount = $deposit_value;
		}

		$deposit_text = $this->helper->getOptionValue( 'bdfw_deposit_label' ) . ': '. wc_price( $deposit_amount ). ' ' . $this->helper->getOptionValue( 'bdfw_per_item_label' );

		// Generate custom text if exists
		$custom_text = '';
		$deposit_custom_text = $this->helper->getOptionValue('bdfw_deposit_notice_custom_text');
		if ( ! empty( $deposit_custom_text ) ) {
			$custom_text = $this->replacePlaceholders( $deposit_custom_text, $product_id );
		}

		return array(
			'deposit_amount' => $deposit_amount,
			'deposit_text' => $deposit_text,
			'custom_text' => $custom_text,
			'is_deposit_forced' => $product_force_deposit,
			'deposit_enabled' => $product_enable_deposit,
			'deposit_type' => $deposit_type,
			'deposit_value' => $deposit_value
		);
	}

	/**
	 * Get the selected variation ID for variable products
	 * @since 1.0.0
	 * @param array $post The POST data
	 * @return int|null The variation ID or null if not found
	 */
	private function get_selected_variation_id( array $post ) {
		// Try to get variation ID from various sources
		$variation_id = null;
		
		// Check if variation_id is in POST data (form submission)
		if ( isset( $post['variation_id'] ) && !empty( $post['variation_id'] ) ) {
			$variation_id = intval( $post['variation_id'] );
		}
		
		return $variation_id;
	}

	/**
	 * Replace placeholders in a string with data from a WooCommerce product.
	 * @since 1.0.0
	 * @param string $template The text from the admin with the placeholders.
	 * @param int $product_id The ID of the product.
	 * @return string The text with the real data.
	 */
	public function replacePlaceholders( $template, $product_id ) {
		// Get the product object
		$product = wc_get_product( $product_id );
		if ( ! $product instanceof \WC_Product ) {
			return $template; // Return original template if product not found
		}

		$deposit_display_value = '';

		$product_enable_deposit = get_post_meta( $product_id, '_bdfwbp_enable_deposit', true ) === 'yes';

		if ( $product_enable_deposit ) {
			$deposit_type = get_post_meta( $product_id, '_bdfwbp_deposits_type', true );
			$deposit_value = get_post_meta( $product_id, '_bdfwbp_deposits_value', true );

			if ( $deposit_type === 'percentage' ) {
				$deposit_display_value = $deposit_value.'%';
			} elseif ( $deposit_type === 'fixed_amount' ) {
				$deposit_display_value = wc_price( (float)$deposit_value );
			}
		}
		else {
			$global_deposit_type = $this->helper->getOptionValue( 'global_deposit_type' );

			if ( $global_deposit_type === 'percentage' ) {
				$deposit_display_value = $this->helper->getOptionValue( 'global_deposit_percentage' ).'%';
			} elseif ( $global_deposit_type === 'fixed_amount' ) {
				$deposit_display_value = wc_price( $this->helper->getOptionValue( 'global_deposit_fixed_amount' ) );
			}
		}

        $next_payment_date = $this->helper->getNextPaymentDate();

		$placeholders = array(
			'{deposit_display_value}',
			'{next_payment_date}'
		);

		$values = array(
			$deposit_display_value,
			$next_payment_date,
		);

		$final_text = str_replace( $placeholders, $values, $template );

		return $final_text;
	}

}