<?php

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

if ( ! class_exists( 'AIEO_Pixel_Display' ) ) :

class AIEO_Pixel_Display {

	const HANDLE = 'aieo-fb-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_add_to_cart', array( $this, 'stash_add_to_cart' ), 10, 4 );
		add_action( 'woocommerce_thankyou', array( $this, 'on_thankyou' ), 20, 1 );
	}

	
	
	

	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['fb_mode'] ) ? $config['fb_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 ) {
		if ( class_exists( 'AIEO_CAPI_Sender' ) && method_exists( 'AIEO_CAPI_Sender', 'resolve_credentials' ) ) {
			$c = AIEO_CAPI_Sender::resolve_credentials( $config );
			return isset( $c['pixel_id'] ) ? (string) $c['pixel_id'] : '';
		}
		return isset( $config['fb_pixel_id'] ) ? trim( (string) $config['fb_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-fb-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,
			'mode'     => isset( $config['fb_mode'] ) ? $config['fb_mode'] : 'off',
			'currency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'EUR',
		);

		
		
		
		
		
		
		$am = $this->advanced_matching();
		if ( ! empty( $am ) ) {
			$payload['am'] = $am;
		}

		
		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_ids' => array( (string) $pid ),
					'value'       => '' !== $product->get_price() ? (float) $product->get_price() : 0,
				);
			}
		}

		
		$on_received = function_exists( 'is_wc_endpoint_url' ) && is_wc_endpoint_url( 'order-received' );
		if ( function_exists( 'is_checkout' ) && is_checkout() && ! $on_received && function_exists( 'WC' ) && WC()->cart ) {
			$ids = array();
			$num = 0;
			foreach ( WC()->cart->get_cart() as $ci ) {
				$cpid  = ! empty( $ci['variation_id'] ) ? (int) $ci['variation_id'] : (int) $ci['product_id'];
				$ids[] = (string) $cpid;
				$num  += (int) $ci['quantity'];
			}
			if ( ! empty( $ids ) ) {
				$payload['initiate_checkout'] = array(
					'content_ids' => $ids,
					'value'       => (float) WC()->cart->get_total( 'edit' ),
					'num_items'   => $num,
				);
			}
		}

		
		
		
		if ( function_exists( 'WC' ) && WC()->session ) {
			$atc = WC()->session->get( 'aieo_fb_atc', array() );
			if ( ! empty( $atc ) && is_array( $atc ) ) {
				WC()->session->set( 'aieo_fb_atc', array() );
				$a_ids = array();
				$a_con = array();
				$a_val = 0;
				$a_num = 0;
				foreach ( $atc as $it ) {
					$a_ids[] = (string) $it['id'];
					$a_con[] = array( 'id' => (string) $it['id'], 'quantity' => (int) $it['quantity'] );
					$a_val  += (float) $it['price'] * (int) $it['quantity'];
					$a_num  += (int) $it['quantity'];
				}
				$payload['add_to_cart'] = array(
					'content_ids' => $a_ids,
					'contents'    => $a_con,
					'value'       => round( $a_val, 2 ),
					'num_items'   => $a_num,
				);
			}
		}

		
		if ( function_exists( 'is_search' ) && is_search() ) {
			$q = function_exists( 'get_search_query' ) ? trim( (string) get_search_query() ) : '';
			if ( '' !== $q ) {
				$payload['search'] = array( 'search_string' => $q );
			}
		}

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

	
	private function advanced_matching() {
		if ( ! class_exists( 'AIEO_PII_Hasher' ) ) {
			return array();
		}
		$src = array();

		
		$oid = ( function_exists( 'is_wc_endpoint_url' ) && is_wc_endpoint_url( 'order-received' ) && function_exists( 'get_query_var' ) )
			? absint( get_query_var( 'order-received' ) )
			: 0;
		if ( $oid > 0 && function_exists( 'wc_get_order' ) ) {
			$o = wc_get_order( $oid );
			if ( $o ) {
				$src = array(
					'em'          => $o->get_billing_email(),
					'ph'          => $o->get_billing_phone(),
					'fn'          => $o->get_billing_first_name(),
					'ln'          => $o->get_billing_last_name(),
					'ct'          => $o->get_billing_city(),
					'st'          => $o->get_billing_state(),
					'zp'          => $o->get_billing_postcode(),
					'country'     => $o->get_billing_country(),
					'external_id' => (int) $o->get_customer_id() > 0 ? (string) $o->get_customer_id() : '',
				);
			}
		}

		
		if ( empty( $src ) && is_user_logged_in() && class_exists( 'WC_Customer' ) ) {
			$uid = get_current_user_id();
			try {
				$c     = new WC_Customer( $uid );
				$email = $c->get_billing_email();
				if ( '' === $email ) {
					$u     = get_userdata( $uid );
					$email = $u ? $u->user_email : '';
				}
				$src = array(
					'em'          => $email,
					'ph'          => $c->get_billing_phone(),
					'fn'          => $c->get_billing_first_name(),
					'ln'          => $c->get_billing_last_name(),
					'ct'          => $c->get_billing_city(),
					'st'          => $c->get_billing_state(),
					'zp'          => $c->get_billing_postcode(),
					'country'     => $c->get_billing_country(),
					'external_id' => (string) $uid,
				);
			} catch ( \Exception $e ) {
				$src = array();
			}
		}

		if ( empty( $src ) ) {
			return array();
		}

		$am = array();
		foreach ( $src as $k => $raw ) {
			$n = AIEO_PII_Hasher::normalize( $k, (string) $raw );
			if ( '' !== $n ) {
				$am[ $k ] = $n;
			}
		}
		return $am;
	}

	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_CAPI_Sender' ) && method_exists( 'AIEO_CAPI_Sender', 'get_or_mint_event_id' ) )
			? AIEO_CAPI_Sender::get_or_mint_event_id( $order )
			: (string) $order->get_meta( '_aieo_fb_event_id' );
		if ( '' === $eid ) {
			return;
		}

		$content_ids = array();
		$contents    = array();
		$num_items   = 0;
		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();
			$num_items    += $qty;
			$content_ids[] = (string) $pid;
			$contents[]    = array(
				'id'       => (string) $pid,
				'quantity' => $qty,
			);
		}

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

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

	
	public function stash_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id ) {
		unset( $cart_item_key );
		if ( ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) || ! function_exists( 'WC' ) || ! WC()->session ) {
			return;
		}
		$pid     = $variation_id ? (int) $variation_id : (int) $product_id;
		$product = ( $pid && function_exists( 'wc_get_product' ) ) ? wc_get_product( $pid ) : null;
		if ( ! is_a( $product, 'WC_Product' ) ) {
			return;
		}
		$pending   = WC()->session->get( 'aieo_fb_atc', array() );
		$pending   = is_array( $pending ) ? $pending : array();
		$pending[] = array(
			'id'       => $pid,
			'quantity' => max( 1, (int) $quantity ),
			'price'    => '' !== $product->get_price() ? (float) $product->get_price() : 0,
		);
		WC()->session->set( 'aieo_fb_atc', $pending );
	}
}

endif;
