<?php

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

class AIEO_Order_Origin_Email {

	public static function register() {
		add_action( 'woocommerce_email_before_order_table', array( __CLASS__, 'render' ), 15, 4 );
	}

	public static function render( $order, $sent_to_admin = false, $plain_text = false, $email = null ) {
		if ( ! $sent_to_admin ) {
			return; 
		}
		if ( ! is_object( $order ) || ! method_exists( $order, 'get_id' ) || ! method_exists( $order, 'get_meta' ) ) {
			return;
		}
		
		
		
		try {
			$info = self::origin_info( $order );
			if ( $plain_text ) {
				echo "\n" . self::render_plain( $info ) . "\n"; 
			} else {
				echo self::render_html( $info ); 
			}
		} catch ( \Throwable $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'AIEO_Order_Origin_Email render skipped: ' . $e->getMessage() );
			}
		}
	}

	private static function origin_info( $order ) {
		$oid = (int) $order->get_id();

		
		$slug     = (string) $order->get_meta( '_aieo_moi_vendor_slug' );
		$provider = (string) $order->get_meta( '_aieo_moi_provider' );
		if ( '' !== $slug || '' !== $provider ) {
			return array(
				'marketplace' => true,
				'origin'      => self::marketplace_label( '' !== $provider ? $provider : $slug ),
				'code'        => (string) $order->get_meta( '_aieo_moi_remote_code' ),
				'state'       => (string) $order->get_meta( '_aieo_moi_state' ),
			);
		}

		
		
		$is_phone = class_exists( 'AIEO_DMM_Phone_Orders' )
			? AIEO_DMM_Phone_Orders::is_phone_order( $order )
			: ( 'yes' === (string) $order->get_meta( '_phone_order' ) || 'admin' === (string) $order->get_meta( '_wc_order_attribution_source_type' ) );
		if ( $is_phone ) {
			return array(
				'marketplace' => false,
				'origin'      => __( 'Site', 'ai-eshop-optimizer' ),
				'channel'     => 'phone_orders',
				'campaign'    => '',
				'source'      => '',
				'medium'      => '',
				'content'     => '',
				'term'        => '',
			);
		}

		
		$channel = $campaign = $source = $medium = '';
		if ( class_exists( 'AIEO_Order_Facts' ) ) {
			$f        = AIEO_Order_Facts::get( $oid );
			$channel  = (string) ( $f['channel'] ?? '' );
			$campaign = (string) ( $f['utm_campaign'] ?? '' );
			$source   = (string) ( $f['utm_source'] ?? '' );
			$medium   = (string) ( $f['utm_medium'] ?? '' );
		}
		$src_type = (string) $order->get_meta( '_wc_order_attribution_source_type' );
		if ( '' === $source )   { $source   = (string) $order->get_meta( '_wc_order_attribution_utm_source' ); }
		if ( '' === $medium )   { $medium   = (string) $order->get_meta( '_wc_order_attribution_utm_medium' ); }
		if ( '' === $campaign ) { $campaign = (string) $order->get_meta( '_wc_order_attribution_utm_campaign' ); }
		
		
		$content = (string) $order->get_meta( '_wc_order_attribution_utm_content' );
		$term    = (string) $order->get_meta( '_wc_order_attribution_utm_term' );
		if ( '' === $channel ) {
			$channel = self::channel_from_wc( $src_type, $source, $medium );
		}

		return array(
			'marketplace' => false,
			'origin'      => __( 'Site', 'ai-eshop-optimizer' ),
			'channel'     => $channel,
			'campaign'    => $campaign,
			'source'      => $source,
			'medium'      => $medium,
			'content'     => $content,
			'term'        => $term,
		);
	}

	private static function marketplace_label( $key ) {
		$key = strtolower( trim( $key ) );
		$map = array(
			'shopflix' => 'Shopflix',
			'skroutz'  => 'Skroutz',
			'emag'     => 'eMAG',
		);
		if ( isset( $map[ $key ] ) ) {
			return $map[ $key ];
		}
		return ucwords( str_replace( array( '_', '-' ), ' ', $key ) );
	}

	private static function channel_label( $channel ) {
		
		return AIEO_Attribution_Block::channel_label( $channel );
	}

	
	private static function channel_from_wc( $src_type, $source, $medium ) {
		$src_type = strtolower( (string) $src_type );
		$source   = strtolower( (string) $source );
		$medium   = strtolower( (string) $medium );
		if ( 'utm' === $src_type || '' !== $medium ) {
			if ( false !== strpos( $medium, 'cpc' ) || false !== strpos( $medium, 'paid' ) || false !== strpos( $medium, 'ppc' ) ) {
				if ( false !== strpos( $source, 'google' ) ) { return 'paid_google'; }
				if ( false !== strpos( $source, 'facebook' ) || false !== strpos( $source, 'instagram' ) || false !== strpos( $source, 'meta' ) || false !== strpos( $source, 'fb' ) ) { return 'paid_facebook'; }
				if ( false !== strpos( $source, 'tiktok' ) ) { return 'paid_tiktok'; }
				if ( false !== strpos( $source, 'bing' ) || false !== strpos( $source, 'microsoft' ) ) { return 'paid_microsoft'; }
				return '' !== $source ? 'paid_' . preg_replace( '/[^a-z0-9]+/', '', $source ) : 'paid';
			}
			if ( false !== strpos( $medium, 'email' ) || false !== strpos( $source, 'newsletter' ) || false !== strpos( $source, 'klaviyo' ) ) { return 'newsletter'; }
			if ( false !== strpos( $medium, 'social' ) ) { return 'social'; }
		}
		if ( 'organic' === $src_type ) { return 'organic_search'; }
		if ( 'referral' === $src_type ) { return 'referral'; }
		if ( 'typein' === $src_type || 'direct' === $src_type || '(direct)' === $src_type ) { return 'direct'; }
		return $src_type;
	}

	private static function rows( array $info ) {
		$rows = array();
		if ( ! empty( $info['marketplace'] ) ) {
			$rows[ __( 'Origin', 'ai-eshop-optimizer' ) ] = $info['origin'] . ' ' . __( '(marketplace)', 'ai-eshop-optimizer' );
			if ( ! empty( $info['code'] ) )  { $rows[ __( 'Marketplace code', 'ai-eshop-optimizer' ) ]  = $info['code']; }
			if ( ! empty( $info['state'] ) ) { $rows[ __( 'Marketplace state', 'ai-eshop-optimizer' ) ] = $info['state']; }
		} else {
			$rows[ __( 'Origin', 'ai-eshop-optimizer' ) ]  = $info['origin'];
			$rows[ __( 'Channel', 'ai-eshop-optimizer' ) ] = self::channel_label( $info['channel'] );
			
			
			$rows += AIEO_Attribution_Block::utm_rows( array(
				'utm_source'   => $info['source'],
				'utm_medium'   => $info['medium'],
				'utm_campaign' => $info['campaign'],
				'utm_content'  => $info['content'],
				'utm_term'     => isset( $info['term'] ) ? $info['term'] : '',
			) );
		}
		return $rows;
	}

	private static function render_html( array $info ) {
		$accent = ! empty( $info['marketplace'] ) ? AIEO_Attribution_Block::ACCENT_MARKETPLACE : AIEO_Attribution_Block::ACCENT_SITE;
		return AIEO_Attribution_Block::render_html( __( 'Order origin & attribution', 'ai-eshop-optimizer' ), self::rows( $info ), $accent );
	}

	private static function render_plain( array $info ) {
		return AIEO_Attribution_Block::render_plain( __( 'Order origin & attribution', 'ai-eshop-optimizer' ), self::rows( $info ) );
	}
}
