<?php

/**
 * GT BOGO Engine — Savings Calculator Superpower
 * Displays real-time savings breakdown in cart totals and on product pages.
 * Shows: original total, discount applied, amount saved, deal tier info.
 * Inherits theme styles. Off by default.
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class GT_BOGO_Savings_Calculator {
 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound
	private $id           = 'savings_calculator';
	private ?array $_cfg  = null;
	private ?array $_anim = null;
	public function __construct() {
		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
			return;
		}
		if ( ! $this->enabled() ) {
			return;
		}
		if ( class_exists( 'GT_BOGO_Attribution_Engine' ) ) {
			GT_BOGO_Attribution_Engine::record_impression( $this->id );
		}
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
		add_filter( 'woocommerce_add_to_cart_fragments', array( $this, 'cart_fragment' ) );
		add_action( 'template_redirect', array( $this, 'register_hooks' ), 5 );
		// Wire Animation Engine
		if ( class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
			if ( $cfg['animate'] && class_exists( 'GT_BOGO_Animation_Engine' ) ) {
				add_action( 'wp_footer', array( 'GT_BOGO_Animation_Engine', 'enqueue' ), 5 );
			}
		}
	}

	/**
	 * Get AI-generated copy for a field, with fallback to default.
	 * Reads from gtbogo_sp_{id}_ai_copy option set by GT_BOGO_AI_Copywriter.
	 *
	 * @param string $field   Copy field name (headline, message, cta, badge_text, etc.)
	 * @param string $default Default text if AI copy not available
	 * @return string
	 * @since 5.0.0
	 */
	private function ai_copy( string $field, string $default = '' ): string {
		$copy = get_option( 'gtbogo_sp_' . $this->id . '_ai_copy', array() );
		return ! empty( $copy[ $field ] ) ? wp_kses_post( $copy[ $field ] ) : $default;
	}


	private function enabled() {

		// ── Orchestrator: autonomous enable/intensity decision ─────────────
		if ( class_exists( 'GT_BOGO_Superpower_Orchestrator' ) ) {
			$orch = GT_BOGO_Superpower_Orchestrator::decision( $this->id );
			if ( isset( $orch['enabled'] ) && ! $orch['enabled'] ) {
				return false;
			}
		}
		return (bool) get_option( 'gtbogo_sp_' . $this->id . '_enabled', 0 )
			&& get_option( 'gtbogo_sp_' . $this->id . '_intensity', 'subtle' ) !== 'off';
	}
	private function intensity(): string {
		if ( class_exists( 'GT_BOGO_Superpower_Orchestrator' ) ) {
			$d = GT_BOGO_Superpower_Orchestrator::decision( $this->id );
			if ( ! empty( $d['intensity'] ) ) {
				return $d['intensity'];
			}
		}
		return get_option( 'gtbogo_sp_' . $this->id . '_intensity', 'subtle' );
	}

	private function cfg(): array {
		if ( $this->_cfg === null && class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$this->_cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
		}
		return $this->_cfg ?? array();
	}

	private function anim(): array {
		if ( $this->_anim === null && class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$this->_anim = GT_BOGO_Superpower_Theme_Intelligence::animation_profile( $this->cfg() );
		}
		return $this->_anim ?? array(
			'use_gamification' => false,
			'use_entrance'     => false,
			'use_micro'        => true,
			'gamif_intensity'  => 'subtle',
			'speed_token'      => 'var(--gtbogo-sp-duration-subtle,350ms)',
			'ease_token'       => 'var(--gtbogo-sp-ease-subtle,ease)',
			'family'           => 'universal',
		);
	}


	private function styles(): array {
		if ( class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( $this->id );
			$m   = $cfg['multipliers'] ?? array();
			return array(
				'font_size' => $m['font_size'],
				'padding'   => $m['padding_v'] . 'px ' . $m['padding_h'] . 'px',
				'opacity'   => (string) $m['opacity'],
			);
		}
		// Token-based fallback — Theme Intelligence always loaded in production
		return array(
			'font_size' => 'var(--gtbogo-sp-fs-base,0.87em)',
			'padding'   => 'var(--gtbogo-sp-pad-v,12px) var(--gtbogo-sp-pad-h,18px)',
			'opacity'   => 'var(--gtbogo-sp-opacity-secondary,0.65)',
		);
	}
	public function enqueue(): void {
		if ( ! function_exists( 'is_cart' ) ) {
			return;
		}
		if ( ! is_cart() && ! is_checkout() ) {
			return;
		}
		wp_add_inline_style(
			'woocommerce-general',
			'
        .gtbogo-savings-calc{font-family:inherit;color:inherit;border-left:3px solid var(--gtbogo-sp-accent,currentColor)}
        .gtbogo-sc-row{display:flex;justify-content:space-between;align-items:center;margin-bottom:5px;font-size:var(--gtbogo-sp-fs-base,0.95em)}
        .gtbogo-sc-row:last-child{margin-bottom:0;font-weight:var(--gtbogo-sp-fw-ui,700);padding-top:5px;border-top:1px solid var(--gtbogo-sp-accent-border,currentColor);opacity:0.8}
        .gtbogo-sc-label{opacity:var(--gtbogo-sp-opacity-secondary,0.65)}
        .gtbogo-sc-value{font-weight:var(--gtbogo-sp-fw-ui,600)}
        .gtbogo-sc-saved{font-weight:var(--gtbogo-sp-fw-ui,700);color:var(--gtbogo-sp-accent,inherit)}
        @media(prefers-reduced-motion:no-preference){
            .gtbogo-savings-calc{transition:opacity var(--gtbogo-sp-duration-subtle,0.4s) ease}
        }
        '
		);
	}

	public function register_hooks(): void {
		if ( class_exists( 'GT_BOGO_Blocks_Compat' ) && GT_BOGO_Blocks_Compat::is_blocks_page() ) {
			add_action( 'wp_footer', array( $this, 'register_blocks_injection' ), 10 );
		} else {
			add_action( 'woocommerce_cart_totals_before_order_total', array( $this, 'render_cart' ) );
			add_action( 'woocommerce_review_order_before_order_total', array( $this, 'render_cart' ) );
		}
	}

	public function register_blocks_injection(): void {
		if ( ! class_exists( 'GT_BOGO_Frontend_Injector' ) ) {
			return;
		}
		ob_start();
		$this->render_cart();
		$html = ob_get_clean();
		if ( empty( trim( $html ) ) ) {
			return;
		}
		$selector = GT_BOGO_Blocks_Compat::is_blocks_checkout()
			? '.wc-block-components-totals-footer-item'
			: '.wc-block-cart__totals-title';
		GT_BOGO_Frontend_Injector::register(
			'gtbogo-savings-calculator',
			$selector,
			$html,
			'before',
			10
		);
	}

	public function cart_fragment( $frags ): array {
		ob_start();
		$this->render_cart();
		$html = ob_get_clean();
		// Always output wrapper so WC AJAX can replace selector cleanly
		if ( empty( trim( $html ) ) ) {
			$html = '<div class="gtbogo-savings-calc" style="display:none"></div>';
		}
		$frags['.gtbogo-savings-calc'] = $html;
		return $frags;
	}
	public function render_cart(): void {
		if ( ! WC()->cart ) {
			return;
		}
		// ── Margin Intelligence: suppress if too thin ──────────────────────
		if ( class_exists( 'GT_BOGO_Cart_Value_Intelligence' ) ) {
			$ratio = GT_BOGO_Cart_Value_Intelligence::get_cart_margin_ratio();
			if ( $ratio !== null && $ratio < 0.20 ) {
				return;
			}
		}
		// BOGO discounts are applied as negative fees — aggregate fee amounts
		$discount = 0.0;
		foreach ( WC()->cart->get_fees() as $fee ) {
			if ( $fee->amount < 0 ) {
				$discount += abs( (float) $fee->amount );
			}
		}
		// Also include WC coupon discounts for stores that use both
		$discount += (float) WC()->cart->get_discount_total();
		if ( $discount < 0.01 ) {
			echo '<div class="gtbogo-savings-calc" style="display:none"></div>';
			return; }
		$subtotal = (float) WC()->cart->get_cart_contents_total();
		$s        = $this->styles();

		// ── Signal Bus: composite urgency label ───────────────────────────────
		$signal_label = '';
		if ( class_exists( 'GT_BOGO_Signal_Bus' ) ) {
			$score = GT_BOGO_Signal_Bus::composite_score();
			if ( $score >= 1.3 ) {
				$signal_label = __( 'High-demand deal — limited availability', 'gt-bogo-engine' );
			} elseif ( $score >= 1.1 ) {
				$signal_label = __( 'This deal is popular right now', 'gt-bogo-engine' );
			}
		}

		// ── Profile Tracker: lifetime savings for logged-in users ─────────────
		$lifetime_savings = 0.0;
		if ( is_user_logged_in() && class_exists( 'GT_BOGO_Customer_Profile_Tracker' ) ) {
			$profile = GT_BOGO_Customer_Profile_Tracker::get_profile( get_current_user_id() );
			if ( $profile ) {
				$lifetime_savings = (float) ( $profile->total_spent ?? 0 );
			}
		}
		?>
		<div class="gtbogo-savings-calc" style="<?php echo esc_attr( GT_BOGO_Superpower_Theme_Intelligence::style_attr( $this->cfg(), array( 'margin-bottom' => '10px' ) ) ); ?>">
			<?php if ( $signal_label ) : ?>
			<div class="gtbogo-sc-row" style="margin-bottom:8px">
				<span class="gtbogo-sc-label" style="font-style:italic;color:var(--gtbogo-sp-accent,inherit)"><?php echo esc_html( $signal_label ); ?></span>
			</div>
			<?php endif; ?>
			<div class="gtbogo-sc-row">
				<span class="gtbogo-sc-label"><?php esc_html_e( 'Cart subtotal', 'gt-bogo-engine' ); ?></span>
				<span class="gtbogo-sc-value"><?php echo wp_kses_post( wc_price( $subtotal ) ); ?></span>
			</div>
			<div class="gtbogo-sc-row">
				<span class="gtbogo-sc-label"><?php esc_html_e( 'Deal discount', 'gt-bogo-engine' ); ?></span>
				<span class="gtbogo-sc-saved">&minus;<?php echo wp_kses_post( wc_price( $discount ) ); ?></span>
			</div>
			<div class="gtbogo-sc-row">
				<span class="gtbogo-sc-label"><?php esc_html_e( 'You save', 'gt-bogo-engine' ); ?></span>
				<span class="gtbogo-sc-saved"><?php echo wp_kses_post( wc_price( $discount ) ); ?></span>
			</div>
			<?php
			// ── LTV/RFM: tier-aware label ────────────────────────────────────
			$sc_ltv  = is_user_logged_in() && class_exists( 'GT_BOGO_LTV_Scoring' ) ? GT_BOGO_LTV_Scoring::get_score( get_current_user_id() ) : 0.0;
			$sc_rfm  = is_user_logged_in() && class_exists( 'GT_BOGO_Repeat_Prediction' ) ? GT_BOGO_Repeat_Prediction::get_score( get_current_user_id() ) : 0.0;
			$sc_tier = '';
			if ( $sc_ltv >= 2500 || $sc_rfm >= 4.0 ) {
				$sc_tier = __( 'Platinum member savings', 'gt-bogo-engine' );
			} elseif ( $sc_ltv >= 1000 || $sc_rfm >= 3.5 ) {
				$sc_tier = __( 'VIP member savings', 'gt-bogo-engine' );
			} elseif ( $sc_ltv >= 500 ) {
				$sc_tier = __( 'Gold member savings', 'gt-bogo-engine' );
			}
			?>
			<?php if ( $sc_tier ) : ?>
			<div class="gtbogo-sc-row" style="font-size:var(--gtbogo-sp-fs-base,0.8em);opacity:var(--gtbogo-sp-opacity-muted,0.45);border-top:none;font-style:italic">
				<span><?php echo esc_html( $sc_tier ); ?></span>
			</div>
			<?php endif; ?>
			<?php if ( $lifetime_savings > 0 ) : ?>
			<div class="gtbogo-sc-row" style="opacity:var(--gtbogo-sp-opacity-secondary,0.55);font-size:var(--gtbogo-sp-fs-base,0.85em);margin-top:4px;border-top:none">
				<span class="gtbogo-sc-label"><?php esc_html_e( 'Your lifetime savings with us', 'gt-bogo-engine' ); ?></span>
				<span class="gtbogo-sc-value"><?php echo wp_kses_post( wc_price( $lifetime_savings ) ); ?></span>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}
	public function render_product(): void {
		if ( class_exists( 'GT_BOGO_Attribution_Engine' ) ) {
			GT_BOGO_Attribution_Engine::record_impression( $this->id );
		}
		global $product;
		if ( ! $product ) {
			return;
		}
		$rule = null;
		if ( function_exists( 'gt_bogo_has_pro' ) && gt_bogo_has_pro() ) {
			$rule = GT_BOGO_Rule_Cache::get_top_active();
		}
		if ( ! $rule ) {
			return;
		}
		$price = (float) $product->get_price();
		if ( $price <= 0 ) {
			return;
		}
		$buy  = (int) $rule['buy_quantity'];
		$get  = (int) $rule['get_quantity'];
		$disc = (float) $rule['discount_value'];
		$type = $rule['discount_type'] ?? 'percent';
		$save = $type === 'percent' ? $price * $get * ( $disc / 100 ) : min( $disc * $get, $price * $get );
		if ( $save < 0.01 ) {
			return;
		}
		$s = $this->styles();
		?>
		<div class="gtbogo-savings-calc" style="<?php echo esc_attr( GT_BOGO_Superpower_Theme_Intelligence::style_attr( $this->cfg(), array( 'margin' => '10px 0' ) ) ); ?>">
			<div class="gtbogo-sc-row">
				<span class="gtbogo-sc-label">
					<?php
					// translators: %1$d is buy quantity, %2$d is get quantity.
					printf( esc_html__( 'Buy %1$d Get %2$d deal saves you', 'gt-bogo-engine' ), (int) $buy, (int) $get );
					?>
				</span>
				<span class="gtbogo-sc-saved"><?php echo wp_kses_post( wc_price( $save ) ); ?></span>
			</div>
		</div>
		<?php
	}
}
