<?php

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

if ( ! class_exists( 'AIEO_TikTok_Pixel_Display' ) ) :

class AIEO_TikTok_Pixel_Display {

	const HANDLE = 'aieo-tiktok-pixel';

	
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function register_display() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_base' ) );
		add_action( 'woocommerce_thankyou', array( $this, 'on_thankyou' ), 22, 1 );
		
		
		
		add_filter( 'rocket_delay_js_exclusions', array( $this, 'rocket_exclusions' ) );
		add_filter( 'rocket_exclude_defer_js', array( $this, 'rocket_exclusions' ) );
	}

	
	public function rocket_exclusions( $excluded ) {
		$excluded = is_array( $excluded ) ? $excluded : array();
		if ( ! $this->browser_enabled( $this->config() ) ) {
			return $excluded;
		}
		$excluded[] = 'aieo-tiktok-pixel';  
		$excluded[] = 'aieoTtPixel';        
		return $excluded;
	}

	private function config() {
		if ( class_exists( 'AIEO_DMM_Conversions' ) && method_exists( 'AIEO_DMM_Conversions', 'get_config' ) ) {
			return AIEO_DMM_Conversions::get_config();
		}
		$o = get_option( 'aieo_dmm_conversions', array() );
		return is_array( $o ) ? $o : array();
	}

	private function browser_enabled( $config ) {
		$mode = isset( $config['tiktok_mode'] ) ? $config['tiktok_mode'] : 'off';
		return in_array( $mode, array( 'browser', 'both' ), true );
	}

	private function consent_blocks() {
		if ( ! class_exists( 'AIEO_Session_Tracker' ) ) {
			return false;
		}
		if ( method_exists( 'AIEO_Session_Tracker', 'is_marketing_consent_blocking' ) ) {
			return AIEO_Session_Tracker::is_marketing_consent_blocking();
		}
		if ( method_exists( 'AIEO_Session_Tracker', 'is_consent_blocking_writes' ) ) {
			return AIEO_Session_Tracker::is_consent_blocking_writes();
		}
		return false;
	}

	private function pixel_id( $config ) {
		return isset( $config['tiktok_pixel_id'] ) ? trim( (string) $config['tiktok_pixel_id'] ) : '';
	}

	private function js_src_and_ver() {
		$file = wp_normalize_path( __FILE__ );
		$pdir = wp_normalize_path( WP_PLUGIN_DIR );
		$tail = ltrim( str_replace( $pdir, '', $file ), '/' );
		$slug = explode( '/', $tail )[0];
		$rel  = 'assets/js/aieo-tiktok-pixel.js';
		$src  = plugins_url( $rel, $pdir . '/' . $slug . '/loader.php' );
		$path = $pdir . '/' . $slug . '/' . $rel;
		$ver  = file_exists( $path ) ? filemtime( $path ) : '1';
		return array( $src, $ver );
	}

	public function enqueue_base() {
		$config = $this->config();
		if ( ! $this->browser_enabled( $config ) || $this->consent_blocks() ) {
			return;
		}
		$pixel_id = $this->pixel_id( $config );
		if ( '' === $pixel_id ) {
			return;
		}
		list( $src, $ver ) = $this->js_src_and_ver();
		wp_enqueue_script( self::HANDLE, $src, array(), $ver, true );

		$payload = array(
			'pixel_id' => $pixel_id,
			'consent'  => 1,
			'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'EUR',
		);

		
		if ( function_exists( 'is_product' ) && is_product() && function_exists( 'wc_get_product' ) ) {
			$pid     = (int) get_queried_object_id();
			$product = $pid ? wc_get_product( $pid ) : null;
			if ( $product ) {
				$payload['view_content'] = array(
					'content_id' => (string) $pid,
					'value'      => '' !== $product->get_price() ? (float) $product->get_price() : 0,
				);
			}
		}

		wp_localize_script( self::HANDLE, 'aieoTtPixel', $payload );
	}

	public function on_thankyou( $order_id ) {
		$order_id = (int) $order_id;
		if ( $order_id <= 0 || ! function_exists( 'wc_get_order' ) ) {
			return;
		}
		$config = $this->config();
		if ( ! $this->browser_enabled( $config ) || $this->consent_blocks() ) {
			return;
		}
		if ( '' === $this->pixel_id( $config ) ) {
			return;
		}
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		$eid = ( class_exists( 'AIEO_TikTok_Events_Sender' ) && method_exists( 'AIEO_TikTok_Events_Sender', 'get_or_mint_event_id' ) )
			? AIEO_TikTok_Events_Sender::get_or_mint_event_id( $order )
			: (string) $order->get_meta( '_aieo_tt_event_id' );
		if ( '' === $eid ) {
			return;
		}

		$contents = array();
		foreach ( $order->get_items() as $item ) {
			if ( ! is_a( $item, 'WC_Order_Item_Product' ) ) {
				continue;
			}
			$pid = $item->get_variation_id() ? (int) $item->get_variation_id() : (int) $item->get_product_id();
			$qty = (int) $item->get_quantity();
			$contents[] = array(
				'content_id'   => (string) $pid,
				'content_type' => 'product',
				'quantity'     => $qty,
				'price'        => $qty > 0 ? round( (float) $item->get_total() / $qty, 2 ) : (float) $item->get_total(),
			);
		}

		$purchase = array(
			'event_id' => $eid,
			'value'    => (float) $order->get_total(),
			'currency' => $order->get_currency(),
			'contents' => $contents,
		);

		wp_add_inline_script(
			self::HANDLE,
			'window.aieoTtPixelPurchase = ' . wp_json_encode( $purchase ) . ';',
			'before'
		);
	}
}

endif;
