<?php
// IMPORTANT: This plugin is dynamically updated - MODIFICATIONS WILL BE OVERWRITTEN

/**************************************************
 * Name: WooCommerce
 * Description: Automatically track new orders as lead submissions
 *************************************************/

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// - this file is included in a function, and no globals are being set here
// phpcs:disable WordPress.PHP.NoSilencedErrors
// - we're going to silence some errors just to avoid issues in case Woo function names change

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

// Anonymous function just so we can stop early if needed
( function () {

	// Wrapping in try/catch to avoid any fatal errors
	try {

		// Make sure Woo is enabled
		if ( ! class_exists( 'WC_Order' ) || ! is_callable( 'is_order_received_page' ) ) {
			return;
		}

		// Only want this JS on the order received / thank-you page
		if ( ! is_order_received_page() ) {
			return;
		}

		// Make sure we have a good order with items
		global $wp;
		if ( ! is_object( $wp ) || empty( $wp->query_vars ) ) {
			return;
		}
		$order_id = isset( $wp->query_vars['order-received'] ) ? (int) $wp->query_vars['order-received'] : null;
		if ( empty( $order_id ) ) {
			return;
		}
		$order = new WC_Order( $order_id );

		// Sanity check to confirm order exists
		if( empty( $order ) ) {
			return;
		}

		/**
		 * To avoid duplicate order submission entries in LMFX (e.g. user returns to thank you page), we:
		 * 	1. check for a specific meta value
		 * 	2. if meta value doesn't exist, then assume order submission hasn't been tracked yet (otherwise, return early)
		 * 	3. set meta value to prevent future duplicate submissions
		 */
		$already_tracked = $order->get_meta( 'mcfx_wp_order_submission_tracked' );

		// Value of true will appear as "1"
		if( $already_tracked ) {
			return;
		}

		$order->update_meta_data( 'mcfx_wp_order_submission_tracked', true );
		$order->save_meta_data();

		$order_items = @$order->get_items();
		if ( empty( $order_items ) ) {
			return;
		}

		// Prepare product string for tracking
		$products = [];
		foreach ( $order_items as $item ) {
			$product = @$item->get_product();
			if ( is_object( $product ) ) {
				$products[] = sprintf(
					'%s (ID: %s | SKU: %s | QTY: %s)',
					$product->get_name(),
					$product->get_id(),
					$product->get_sku(),
					$item->get_quantity()
				);
			}
		}

		// This is what we'll pass to the RCFX pixel
		$field_data = [
			[
				'name' => 'name',
				'value' => @$order->get_billing_first_name() . ' ' . @$order->get_billing_last_name(),
			],
			[
				'name' => 'email',
				'value' => @$order->get_billing_email(),
			],
			[
				'name' => 'phone',
				'value' => @$order->get_billing_phone(),
			],
			[
				'name' => 'address',
				'value' => @$order->get_billing_address_1() . ' ' . @$order->get_billing_address_2(),
			],
			[
				'name' => 'order_number',
				'value' => @$order->get_order_number(),
			],
			[
				'name' => 'order_total',
				'value' => @$order->get_total(),
			],
			[
				'name' => 'products',
				'value' => $products, // will be consolidated from array to string
			],
		];

		/**
		 * Allow plugins/theme to customize data for RCFX as needed 
		 * 
		 * Return a value of false or null to prevent any data from going to RCFX
		 *
		 * @since 2.6.5
		 *
		 * @param array $field_data Order data to pass to RCFX
		 * @param WC_Order $order Woo order object
		 */
		$field_data = apply_filters( 'mcfx_webfx_wp_core_services_integration_woo_field_data', $field_data, $order );
		
		if( empty( $field_data ) ) {
			return;
		}

		// Combine product data into a nice-to-read string
		foreach( $field_data as &$data_pair ) {
			if( 'products' === $data_pair['name'] && is_array( $data_pair['value'] ) ) {
				$data_pair['value'] = implode( ', ', $data_pair['value'] );
			}
		}
		unset( $data_pair );

		?>

<!-- MCFX Integration: WooCommerce -->
<script type="text/javascript" data-registered="nutshell-plugin">
	( () => {
		const fieldData = <?php echo wp_json_encode( $field_data ); ?>;
		const orderId = `woocommerce-order-${<?php echo esc_js( $order_id ); ?>}`;

		async function mcfxHasLoaded() {
			while( typeof mcfx == 'undefined' || typeof window.mcfxCaptureCustomFormData == 'undefined' ) {
				await new Promise(function(resolve) {
					setTimeout(resolve, 1000);
				});
			};
		}

		mcfxHasLoaded().then( () => {
			if( 'function' === typeof window.mcfxCaptureCustomFormData ) {
				window.mcfxCaptureCustomFormData( fieldData, 'woocommerce-order-received', orderId );
			}
		});
	}) ()
</script>

	<?php

	// Bail out on any error
	} catch( Exception $e ) {
		error_log( $e->getMessage() );
	}


} )();

// IMPORTANT: This plugin is dynamically updated - MODIFICATIONS WILL BE OVERWRITTEN
