<?php

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

class AIEO_DMM_Add_To_Cart_Text extends AIEO_DMM_Module_Base {

	const OPTION_KEY = 'aieo_dmm_add_to_cart_text_settings';

	public function get_id()       { return 'add_to_cart_text'; }
	public function get_label()    { return __( 'Add to Cart Text', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 30; }
	public function get_group()    { return 'product_display'; }

	public function register_hooks() {
		add_action( 'wp_ajax_aieo_dmm_add_to_cart_text_save', array( $this, 'ajax_save' ) );

		$s = $this->get_settings();
		if ( empty( $s['enabled'] ) ) { return; }

		add_filter( 'woocommerce_product_single_add_to_cart_text', array( $this, 'single_add_to_cart_text' ), 99, 2 );
		add_filter( 'woocommerce_product_add_to_cart_text',        array( $this, 'shop_add_to_cart_text' ),   99, 2 );

		
		
		
		add_action( 'wp_head', array( $this, 'emit_frontend_config' ), 1 );
	}

	
	public function emit_frontend_config() {
		
		if ( is_admin() ) { return; }
		$s = $this->get_settings();
		if ( empty( $s['enabled'] ) ) { return; }

		$per_variation = $this->is_per_variation_tracking_enabled();

		$cfg = array(
			'enabled' => true,
			'showQty' => ! empty( $s['show_in_cart_qty'] ),
			'simple'  => array(
				'singleDefault' => ! empty( $s['simple_product_custom_single'] )         ? (string) $s['simple_product_single_label']        : '',
				'singleInCart'  => ! empty( $s['simple_product_in_cart_label_enabled'] ) ? (string) $s['simple_product_in_cart_single_label'] : '',
				'shopDefault'   => (string) $s['simple_product_shop_label'],
				'shopInCart'    => ! empty( $s['simple_product_in_cart_label_enabled'] ) ? (string) $s['simple_product_in_cart_shop_label']   : '',
			),
			'variable' => array(
				'singleDefault' => ! empty( $s['variable_product_custom_single'] )         ? (string) $s['variable_product_single_label']        : '',
				'singleInCart'  => ! empty( $s['variable_product_in_cart_label_enabled'] ) ? (string) $s['variable_product_in_cart_single_label'] : '',
				'shopDefault'   => (string) $s['variable_product_shop_label'],
				'shopInCart'    => ! empty( $s['variable_product_in_cart_label_enabled'] ) ? (string) $s['variable_product_in_cart_shop_label']   : '',
			),
			
			
			
			
			'perVariation' => $per_variation,
		);

		
		
		
		if ( $per_variation ) {
			$map = $this->build_pdp_variation_qty_map();
			if ( ! empty( $map ) ) {
				$cfg['qtyByVariation'] = $map;
			}
		}

		echo "<script>window.aieoAddToCartText=" . wp_json_encode( $cfg ) . ";</script>\n";
	}

	public function get_settings() {
		$stored = get_option( self::OPTION_KEY, array() );
		if ( ! is_array( $stored ) ) { $stored = array(); }
		
		
		$legacy = get_option( 'om_ppe_add-to-cart-text', array() );
		if ( ! is_array( $legacy ) ) { $legacy = array(); }
		return array_merge( array(
			'enabled'                                   => false,
			
			'simple_product_shop_label'                 => 'Add to cart',
			'simple_product_single_label'               => 'Add to cart',
			'simple_product_custom_single'              => false,
			'simple_product_in_cart_label_enabled'      => false,
			'simple_product_in_cart_shop_label'         => 'Add another',
			'simple_product_in_cart_single_label'       => 'Add another',
			
			'variable_product_shop_label'               => 'Select options',
			'variable_product_single_label'             => 'Add to cart',
			'variable_product_custom_single'            => false,
			'variable_product_in_cart_label_enabled'    => false,
			'variable_product_in_cart_shop_label'       => 'Add another',
			'variable_product_in_cart_single_label'     => 'Add another',
			
			'out_of_stock_label'                        => 'Out of stock',
			'out_of_stock_custom_label_enabled'         => false,
			
			
			'show_in_cart_qty'                          => true,
		), $legacy, $stored );
	}

	public function ajax_save() {
		AIEO_DMM::verify_ajax_request();
		$bool = function ( $key ) { return ! empty( $_POST[ $key ] ); };
		$text = function ( $key, $default ) {
			return isset( $_POST[ $key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) : $default;
		};
		update_option( self::OPTION_KEY, array(
			'enabled'                                => $bool( 'enabled' ),
			'simple_product_shop_label'              => $text( 'simple_product_shop_label', 'Add to cart' ),
			'simple_product_single_label'            => $text( 'simple_product_single_label', 'Add to cart' ),
			'simple_product_custom_single'           => $bool( 'simple_product_custom_single' ),
			'simple_product_in_cart_label_enabled'   => $bool( 'simple_product_in_cart_label_enabled' ),
			'simple_product_in_cart_shop_label'      => $text( 'simple_product_in_cart_shop_label', 'Add another' ),
			'simple_product_in_cart_single_label'    => $text( 'simple_product_in_cart_single_label', 'Add another' ),
			'variable_product_shop_label'            => $text( 'variable_product_shop_label', 'Select options' ),
			'variable_product_single_label'          => $text( 'variable_product_single_label', 'Add to cart' ),
			'variable_product_custom_single'         => $bool( 'variable_product_custom_single' ),
			'variable_product_in_cart_label_enabled' => $bool( 'variable_product_in_cart_label_enabled' ),
			'variable_product_in_cart_shop_label'    => $text( 'variable_product_in_cart_shop_label', 'Add another' ),
			'variable_product_in_cart_single_label'  => $text( 'variable_product_in_cart_single_label', 'Add another' ),
			'out_of_stock_label'                     => $text( 'out_of_stock_label', 'Out of stock' ),
			'out_of_stock_custom_label_enabled'      => $bool( 'out_of_stock_custom_label_enabled' ),
			'show_in_cart_qty'                       => $bool( 'show_in_cart_qty' ),
		), false );
		wp_send_json_success( array( 'message' => __( 'Add to Cart Text settings saved.', 'ai-eshop-optimizer' ) ) );
	}

	
	private function get_product_override( $product_id, $key ) {
		$aieo   = (string) get_post_meta( $product_id, '_aieo_add_to_cart_' . $key, true );
		if ( $aieo !== '' ) { return $aieo; }
		
		
		if ( $key === 'single_label' || $key === 'shop_label' ) {
			return (string) get_post_meta( $product_id, '_om_ppe_add_to_cart_' . $key, true );
		}
		return '';
	}

	
	private function is_in_cart( $product ) {
		if ( ! function_exists( 'WC' ) || ! WC()->cart ) { return false; }
		$pid = (int) $product->get_id();
		foreach ( WC()->cart->get_cart() as $item ) {
			$ipid = (int) ( $item['product_id'] ?? 0 );
			$ivid = (int) ( $item['variation_id'] ?? 0 );
			if ( $ipid === $pid || $ivid === $pid ) {
				if ( (int) ( $item['quantity'] ?? 0 ) > 0 ) { return true; }
			}
		}
		return false;
	}

	
	private function build_pdp_variation_qty_map() {
		if ( ! function_exists( 'is_product' ) || ! is_product() )           { return array(); }
		if ( ! function_exists( 'WC' ) || ! WC()->cart )                     { return array(); }
		$qo = function_exists( 'get_queried_object' ) ? get_queried_object() : null;
		if ( ! ( $qo instanceof WP_Post ) || $qo->post_type !== 'product' ) { return array(); }
		$product = function_exists( 'wc_get_product' ) ? wc_get_product( $qo->ID ) : null;
		if ( ! $product || ! $product->is_type( 'variable' ) )               { return array(); }

		$map = array();
		foreach ( (array) $product->get_children() as $vid ) {
			$map[ (int) $vid ] = 0;
		}

		$parent_id = (int) $product->get_id();
		foreach ( WC()->cart->get_cart() as $item ) {
			$ipid = (int) ( $item['product_id'] ?? 0 );
			$ivid = (int) ( $item['variation_id'] ?? 0 );
			if ( $ipid !== $parent_id || $ivid <= 0 ) { continue; }
			$map[ $ivid ] = ( isset( $map[ $ivid ] ) ? $map[ $ivid ] : 0 ) + max( 0, (int) ( $item['quantity'] ?? 0 ) );
		}
		return $map;
	}

	
	private function is_per_variation_tracking_enabled() {
		$swatches = get_option( 'aieo_dmm_swatches_settings', array() );
		if ( ! is_array( $swatches ) ) { $swatches = array(); }
		return ! empty( $swatches['track_per_variation_atc'] );
	}

	public function single_add_to_cart_text( $text, $product ) {
		if ( ! is_a( $product, 'WC_Product' ) ) { return $text; }

		
		
		
		$pid = (int) $product->get_id();
		if ( $this->is_in_cart( $product ) ) {
			$override = $this->get_product_override( $pid, 'in_cart_single_label' );
			if ( $override !== '' ) { return esc_html( $override ); }
		}
		$override = $this->get_product_override( $pid, 'single_label' );
		if ( $override !== '' ) { return esc_html( $override ); }

		$s = $this->get_settings();
		if ( ! function_exists( 'is_product' ) || ! is_product() ) { return $text; }

		$is_simple   = $product->is_type( 'simple' );
		$is_variable = $product->is_type( 'variable' );
		if ( ! $is_simple && ! $is_variable ) { return $text; }

		$prefix     = $is_simple ? 'simple_product_' : 'variable_product_';
		$in_cart    = $this->is_in_cart( $product );
		$ic_enabled = ! empty( $s[ $prefix . 'in_cart_label_enabled' ] );
		if ( $in_cart && $ic_enabled ) {
			return esc_html( (string) $s[ $prefix . 'in_cart_single_label' ] );
		}
		if ( ! empty( $s[ $prefix . 'custom_single' ] ) ) {
			return esc_html( (string) $s[ $prefix . 'single_label' ] );
		}
		return $text;
	}

	public function shop_add_to_cart_text( $text, $product ) {
		if ( ! is_a( $product, 'WC_Product' ) ) { return $text; }
		$s = $this->get_settings();

		
		if ( ! $product->is_in_stock() && ! empty( $s['out_of_stock_custom_label_enabled'] ) ) {
			return esc_html( (string) $s['out_of_stock_label'] );
		}

		$pid = (int) $product->get_id();
		if ( $this->is_in_cart( $product ) ) {
			$override = $this->get_product_override( $pid, 'in_cart_shop_label' );
			if ( $override !== '' ) { return esc_html( $override ); }
		}
		$override = $this->get_product_override( $pid, 'shop_label' );
		if ( $override !== '' ) { return esc_html( $override ); }

		$is_simple   = $product->is_type( 'simple' );
		$is_variable = $product->is_type( 'variable' );
		if ( ! $is_simple && ! $is_variable ) { return $text; }

		$prefix     = $is_simple ? 'simple_product_' : 'variable_product_';
		$in_cart    = $this->is_in_cart( $product );
		$ic_enabled = ! empty( $s[ $prefix . 'in_cart_label_enabled' ] );
		if ( $in_cart && $ic_enabled ) {
			return esc_html( (string) $s[ $prefix . 'in_cart_shop_label' ] );
		}
		return esc_html( (string) $s[ $prefix . 'shop_label' ] );
	}

	public function render_subtab() {
		$s     = $this->get_settings();
		$nonce = wp_create_nonce( AIEO_DMM::NONCE_ACTION );
		$ajax  = admin_url( 'admin-ajax.php' );
		echo '<div class="aieo-dmm-section">';
		echo '<h2>' . esc_html__( 'Add to Cart Text', 'ai-eshop-optimizer' ) . '</h2>';
		echo '<p class="description">' . esc_html__( 'Customise the Add-to-Cart button label per product type, and an alternate label for products already in the shopper\'s cart. Per-product overrides via post-meta `_aieo_add_to_cart_*` (or legacy `_om_ppe_add_to_cart_*`) still win over module-level settings.', 'ai-eshop-optimizer' ) . '</p>';
		echo '<form id="aieo-dmm-actt-form" class="aieo-dmm-form aieo-dmm-card">';
		echo '<table class="form-table">';

		echo '<tr><th>' . esc_html__( 'Enable', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="enabled" value="1" ' . checked( ! empty( $s['enabled'] ), true, false ) . '> ' . esc_html__( 'Apply custom labels site-wide', 'ai-eshop-optimizer' ) . '</label></td></tr>';

		echo '<tr><th>' . esc_html__( 'Show qty badge', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="show_in_cart_qty" value="1" ' . checked( ! empty( $s['show_in_cart_qty'] ), true, false ) . '> ' . esc_html__( 'Append "+N" badge showing how many of this product are already in the cart', 'ai-eshop-optimizer' ) . '</label></td></tr>';

		
		echo '<tr><th colspan="2"><h3 style="margin:8px 0 0;">' . esc_html__( 'Simple products', 'ai-eshop-optimizer' ) . '</h3></th></tr>';
		echo '<tr><th>' . esc_html__( 'Shop page label', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="simple_product_shop_label" value="' . esc_attr( (string) $s['simple_product_shop_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( 'Custom single-page label', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="simple_product_custom_single" value="1" ' . checked( ! empty( $s['simple_product_custom_single'] ), true, false ) . '> ' . esc_html__( 'Use a different label on the single product page', 'ai-eshop-optimizer' ) . '</label></td></tr>';
		echo '<tr><th>' . esc_html__( 'Single page label', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="simple_product_single_label" value="' . esc_attr( (string) $s['simple_product_single_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( '"In cart" label', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="simple_product_in_cart_label_enabled" value="1" ' . checked( ! empty( $s['simple_product_in_cart_label_enabled'] ), true, false ) . '> ' . esc_html__( 'Use a different label when this product is already in the shopper\'s cart', 'ai-eshop-optimizer' ) . '</label></td></tr>';
		echo '<tr><th>' . esc_html__( 'Shop page (in cart)', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="simple_product_in_cart_shop_label" value="' . esc_attr( (string) $s['simple_product_in_cart_shop_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( 'Single page (in cart)', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="simple_product_in_cart_single_label" value="' . esc_attr( (string) $s['simple_product_in_cart_single_label'] ) . '" class="regular-text"></td></tr>';

		
		echo '<tr><th colspan="2"><h3 style="margin:8px 0 0;">' . esc_html__( 'Variable products', 'ai-eshop-optimizer' ) . '</h3></th></tr>';
		echo '<tr><th>' . esc_html__( 'Shop page label', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="variable_product_shop_label" value="' . esc_attr( (string) $s['variable_product_shop_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( 'Custom single-page label', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="variable_product_custom_single" value="1" ' . checked( ! empty( $s['variable_product_custom_single'] ), true, false ) . '></label></td></tr>';
		echo '<tr><th>' . esc_html__( 'Single page label', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="variable_product_single_label" value="' . esc_attr( (string) $s['variable_product_single_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( '"In cart" label', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="variable_product_in_cart_label_enabled" value="1" ' . checked( ! empty( $s['variable_product_in_cart_label_enabled'] ), true, false ) . '> ' . esc_html__( 'Use a different label when any variation of this product is already in the shopper\'s cart', 'ai-eshop-optimizer' ) . '</label></td></tr>';
		echo '<tr><th>' . esc_html__( 'Shop page (in cart)', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="variable_product_in_cart_shop_label" value="' . esc_attr( (string) $s['variable_product_in_cart_shop_label'] ) . '" class="regular-text"></td></tr>';
		echo '<tr><th>' . esc_html__( 'Single page (in cart)', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="variable_product_in_cart_single_label" value="' . esc_attr( (string) $s['variable_product_in_cart_single_label'] ) . '" class="regular-text"></td></tr>';

		
		echo '<tr><th colspan="2"><h3 style="margin:8px 0 0;">' . esc_html__( 'Out of stock', 'ai-eshop-optimizer' ) . '</h3></th></tr>';
		echo '<tr><th>' . esc_html__( 'Custom out-of-stock label', 'ai-eshop-optimizer' ) . '</th><td><label><input type="checkbox" name="out_of_stock_custom_label_enabled" value="1" ' . checked( ! empty( $s['out_of_stock_custom_label_enabled'] ), true, false ) . '></label></td></tr>';
		echo '<tr><th>' . esc_html__( 'Out of stock label', 'ai-eshop-optimizer' ) . '</th><td><input type="text" name="out_of_stock_label" value="' . esc_attr( (string) $s['out_of_stock_label'] ) . '" class="regular-text"></td></tr>';

		echo '</table>';
		echo '<p><button type="button" class="button button-primary" id="aieo-dmm-actt-save">' . esc_html__( 'Save', 'ai-eshop-optimizer' ) . '</button>';
		echo ' <span id="aieo-dmm-actt-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
		echo '</form>';
		echo '<script>(function(){var f=document.getElementById("aieo-dmm-actt-form");var b=document.getElementById("aieo-dmm-actt-save");var s=document.getElementById("aieo-dmm-actt-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_add_to_cart_text_save");fd.set("nonce","' . esc_js( $nonce ) . '");s.style.color="#646970";s.textContent="' . esc_js( __( 'Saving…', 'ai-eshop-optimizer' ) ) . '";fetch("' . esc_js( $ajax ) . '",{method:"POST",credentials:"same-origin",body:fd}).then(function(r){return r.json();}).then(function(j){if(j&&j.success){s.style.color="#15803d";s.textContent=j.data.message;}else{s.style.color="#b91c1c";s.textContent=(j&&j.data&&j.data.message)||"' . esc_js( __( 'Save failed.', 'ai-eshop-optimizer' ) ) . '";}});});})();</script>';
		echo '</div>';
	}
}
