<?php

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}

// Includes
if (file_exists(ASWP_ATHENA_CORE_INC . 'Controller/FullReindexController.php')) {
	include_once ASWP_ATHENA_CORE_INC . 'Controller/FullReindexController.php';
}

if (file_exists(ASWP_ATHENA_CORE_INC . 'Controller/ProductPartialReindexController.php')) {
	include_once ASWP_ATHENA_CORE_INC . 'Controller/ProductPartialReindexController.php';
}

if (file_exists(ASWP_ATHENA_CORE_INC . 'Controller/CartAnalyticsController.php')) {
	include_once ASWP_ATHENA_CORE_INC . 'Controller/CartAnalyticsController.php';
}

if (file_exists(ASWP_ATHENA_CORE_INC . 'Controller/OrderAnalyticsController.php')) {
	include_once ASWP_ATHENA_CORE_INC . 'Controller/OrderAnalyticsController.php';
}
// END Includes

// Shortcode for Athena Search
if (file_exists(__DIR__ . '/Shortcodes/AthenaSearchShortcode.php')) {
	include_once __DIR__ . '/Shortcodes/AthenaSearchShortcode.php';
	$athenaSearchShortcode = new AthenaSearchShortcode();
}

// Shortcode for Athena Search Results
if (file_exists(__DIR__ . '/Shortcodes/AthenaSearchResultsShortcode.php')) {
	include_once __DIR__ . '/Shortcodes/AthenaSearchResultsShortcode.php';
	$athenaSearchResultsShortcode = new AthenaSearchResultsShortcode();
}

// Create plugin admin menu
add_action('admin_menu', 'athena_create_menu');
function athena_create_menu() {
	// Top-level menu
	add_menu_page(
		'Athena Search',
		'Athena Search',
		'administrator',
		'athena_options_slug',
		'athena_configuration_page'
	);

	// Submenu: Configuration
	add_submenu_page(
		'athena_options_slug',
		'Configuration',
		'Configuration',
		'administrator',
		'athena_options_slug',
		'athena_configuration_page'
	);

	// Submenu: User Guide
	add_submenu_page(
		'athena_options_slug',
		'User Guide',
		'User Guide',
		'administrator',
		'athena_user_guide_slug',
		'athena_user_guide_page'
	);

	// Submenu: About Us
	add_submenu_page(
		'athena_options_slug',
		'About Us',
		'About Us',
		'administrator',
		'athena_about_us_slug',
		'athena_about_us_page'
	);

	// Submenu: Help & Support
	add_submenu_page(
		'athena_options_slug',
		'Help & Support',
		'Help & Support',
		'administrator',
		'athena_help_and_support_slug',
		'athena_help_and_support_page'
	);

	add_action('admin_init', 'athena_register_settings');
}
// END Create plugin admin menu

// Add "Settings" link next to "Deactivate" in Plugins page
add_filter('plugin_action_links_' . plugin_basename(dirname(__DIR__) . '/athena-search.php'), 'athena_plugin_action_links');

function athena_plugin_action_links($links) {
	$settings_link = '<a href="' . esc_url(admin_url('admin.php?page=athena_options_slug')) . '">' . __('Settings', 'athena-search') . '</a>';

	$user_guide_link = '<a href="' . esc_url(admin_url('admin.php?page=athena_user_guide_slug')) . '">' . __('User Guide', 'athena-search') . '</a>';

	array_unshift($links, $user_guide_link);
	array_unshift($links, $settings_link);

	return $links;
}

// Register plugin settings
function athena_register_settings() {
	register_setting('athena', 'athena_options');

	add_settings_section(
		'athena_section_credentials',
		'',
		function(){},
		'athena'
	);

	add_settings_field(
		'athena_dashboard_url',
		__('Athena Dashboard Url', 'athena'),
		'athena_field_athena_dashboard_url_cb',
		'athena',
		'athena_section_credentials',
		['label_for'=>'athena_dashboard_url']
	);

	add_settings_field(
		'dashboard_website_token',
		__('Dashboard Website Token', 'athena'),
		'athena_field_dashboard_website_token_cb',
		'athena',
		'athena_section_credentials',
		['label_for'=>'dashboard_website_token']
	);

	add_settings_field(
		'integration_key',
		__('Integration Key', 'athena'),
		'athena_field_integration_key_cb',
		'athena',
		'athena_section_credentials',
		['label_for'=>'integration_key']
	);

	add_settings_field(
		'client_id',
		__('Client ID', 'athena'),
		'athena_field_client_id_cb',
		'athena',
		'athena_section_credentials',
		['label_for'=>'client_id']
	);

	add_settings_field(
		'client_secret',
		__('Client Secret', 'athena'),
		'athena_field_client_secret_cb',
		'athena',
		'athena_section_credentials',
		['label_for'=>'client_secret']
	);

	add_settings_field(
		'athena_landing_page',
		__('Search Landing Page', 'athena'),
		'athena_field_athena_landing_page_cb',
		'athena',
		'athena_section_credentials',
		['label_for' => 'athena_landing_page']
	);
}
// END Register plugin settings

// Scripts
add_action('admin_enqueue_scripts', function($hook) {
	wp_enqueue_style('athena-wp-admin-sidebar', ASWP_PLUGIN_URL . 'public/css/athena-wp-admin-sidebar.css', [], '1.1.0');
	if (strpos($hook, 'athena-search_page_athena_') !== false || $hook === 'toplevel_page_athena_options_slug') {
		// Athena Admin CSS
		wp_enqueue_style('athena-wp-admin', ASWP_PLUGIN_URL . 'public/css/athena-wp-admin.css', [], '1.1.0');

		// Swiper
		wp_enqueue_style('swiper', ASWP_PLUGIN_URL . 'public/swiper/swiper-bundle.min.css', [], '11.0');
		wp_enqueue_script('swiper', ASWP_PLUGIN_URL . 'public/swiper/swiper-bundle.min.js', [], '11.0', true);

		// Athena Admin JS
		wp_enqueue_script('athena-admin-js', ASWP_PLUGIN_URL . 'public/js/athena-wp-admin.js', ['swiper'], '1.0.0', true);
	}
});

add_action('wp_enqueue_scripts', function () {
	wp_enqueue_script('athena-analytics', ASWP_PLUGIN_URL . 'public/js/athena-analytics.js', [], '1.0.0', true);

	$options = get_option('athena_options', []);
	$landing_page_id = intval($options['athena_landing_page'] ?? 0);
	$landing_page_url = $landing_page_id ? get_permalink($landing_page_id) : '';

	wp_localize_script('athena-analytics', 'athenaData', [
		'landingPageUrl' => $landing_page_url,
	]);
});

// Add type="module" to athena-x-ai-index.js script tag
add_filter('script_loader_tag', function ($tag, $handle) {
	if ($handle === 'athena-x-ai-index') {
		$tag = str_replace('<script ', '<script type="module" ', $tag);
	}
	return $tag;
}, 10, 2);

// END Scripts

// Ajax Handler For Configuration Form
add_action('wp_ajax_athena_configuration_form', 'athena_configuration_form_callback');
function athena_configuration_form_callback() {

	if (!current_user_can('manage_options')) {
		wp_send_json_error('You do not have permission to do this.');
	}

	$options = $_POST['athena_options'] ?? [];

	$dashboard_url = sanitize_text_field($options['athena_dashboard_url'] ?? '');
	$token = sanitize_text_field($options['dashboard_website_token'] ?? '');
	$integration_key = sanitize_text_field($options['integration_key'] ?? '');
	$client_id = sanitize_text_field($options['client_id'] ?? '');
	$client_secret = sanitize_text_field($options['client_secret'] ?? '');
	$landing_page = intval($options['athena_landing_page'] ?? 0);

	if (empty($dashboard_url) || empty($token) || empty($client_id) || empty($client_secret)) {
		wp_send_json_error('Please fill in all required fields.');
	}

	$options = [
		'athena_dashboard_url' => $dashboard_url,
		'dashboard_website_token' => $token,
		'integration_key' => $integration_key,
		'client_id' => $client_id,
		'client_secret' => $client_secret,
		'athena_landing_page' => $landing_page,
	];

	$saved = update_option('athena_options', $options);

	if ($saved) {
		wp_send_json_success('Settings saved successfully!');
	} else {
		wp_send_json_error('Failed to save settings. Please try again.');
	}
}
// Ajax Handler For Configuration Form

// Ajax Handler For Contact Form
add_action('wp_ajax_athena_send_contact_email', 'athena_send_contact_email_callback');
function athena_send_contact_email_callback() {
	$name = sanitize_text_field($_POST['athena_name'] ?? '');
	$email = sanitize_email($_POST['athena_email'] ?? '');
	$subject = sanitize_text_field($_POST['athena_subject'] ?? '');
	$title = sanitize_text_field($_POST['athena_title'] ?? '');
	$message = sanitize_textarea_field($_POST['athena_message'] ?? '');

	if (empty($name) || empty($email) || empty($subject) || empty($title) || empty($message)) {
		wp_send_json_error('Please fill in all required fields.');
	}

	$sendMailTo = 'sales@a-x.ai';
	$subject_line = "Athena Enterprise Search Plugin Support - " . ucfirst(str_replace('_', ' ', $subject));
	$body = "
		<strong>Name:</strong> {$name}<br>
		<strong>Email:</strong> {$email}<br>
		<strong>Title:</strong> {$title}<br>
		<strong>Message:</strong><br>" . nl2br($message);

	$headers = array('Content-Type: text/html; charset=UTF-8', "Reply-To: {$name} <{$email}>");

	if (wp_mail($sendMailTo, $subject_line, $body, $headers)) {
		wp_send_json_success('Message sent successfully!');
	} else {
		wp_send_json_error('Email sending failed - your site may not have an email service configured (e.g. via SMTP).');
	}
}
// END Ajax Handler For Contact Form

// Callback functions for each settings input field
function athena_field_athena_dashboard_url_cb($args) {
	$options = get_option('athena_options');
	?>
	<div class="athena-form-field-wrp">
		<input type="url" id="<?php echo esc_attr($args['label_for']); ?>" name="athena_options[<?php echo esc_attr($args['label_for']); ?>]" placeholder="Enter Athena Dashboard Url" value="<?php echo esc_attr($options[$args['label_for']] ?? ''); ?>" required />
		<span class="clear-field"></span>
	</div>
	<?php
}

function athena_field_dashboard_website_token_cb($args) {
	$options = get_option('athena_options');
	?>
	<div class="athena-form-field-wrp">
		<input type="text" id="<?php echo esc_attr($args['label_for']); ?>" name="athena_options[<?php echo esc_attr($args['label_for']); ?>]" placeholder="Enter Dashboard Website Token" value="<?php echo esc_attr($options[$args['label_for']] ?? ''); ?>" required />
		<span class="clear-field"></span>
	</div>
	<?php
}

function athena_field_integration_key_cb($args) {
	$options = get_option('athena_options');
	?>
	<div class="athena-form-field-wrp">
		<input type="text" id="<?php echo esc_attr($args['label_for']); ?>" name="athena_options[<?php echo esc_attr($args['label_for']); ?>]" placeholder="Enter Integration Key" value="<?php echo esc_attr($options[$args['label_for']] ?? ''); ?>" required />
		<span class="clear-field"></span>
	</div>
	<?php
}

function athena_field_client_id_cb($args) {
	$options = get_option('athena_options');
	?>
	<div class="athena-form-field-wrp">
		<input type="text" id="<?php echo esc_attr($args['label_for']); ?>" name="athena_options[<?php echo esc_attr($args['label_for']); ?>]" placeholder="Enter Client ID" value="<?php echo esc_attr($options[$args['label_for']] ?? ''); ?>" required />
		<span class="clear-field"></span>
	</div>
	<?php
}

function athena_field_client_secret_cb($args) {
	$options = get_option('athena_options');
	?>
	<div class="athena-form-field-wrp">
		<input type="password" id="<?php echo esc_attr($args['label_for']); ?>" name="athena_options[<?php echo esc_attr($args['label_for']); ?>]" placeholder="Enter Client Secret" value="<?php echo esc_attr($options[$args['label_for']] ?? ''); ?>" required />
		<span class="clear-field"></span>
	</div>
	<?php
}

function athena_field_athena_landing_page_cb($args) {
	$options = get_option('athena_options');
	$selected_page_id = intval($options['athena_landing_page'] ?? get_option('athena_search_page_id'));

	$pages = get_pages(['post_status' => 'publish']);
	echo '<select id="' . esc_attr($args['label_for']) . '" name="athena_options[' . esc_attr($args['label_for']) . ']" required>';
	printf('<option value="" disabled selected hidden>-- Select Search Landing Page --</option>');
	foreach ($pages as $page) {
		printf(
			'<option value="%1$d" %2$s>%3$s</option>',
			$page->ID,
			selected($selected_page_id, $page->ID, false),
			esc_html($page->post_title)
		);
	}
	echo '</select>';
}
// END Callback functions for each settings input field

// Render Render Settings Page
function athena_configuration_page() {
	if (!current_user_can('manage_options')) {
		return;
	}

	$file = dirname(__DIR__) . '/src/Views/configuration-view.php';
	if (file_exists($file)) {
		include $file;
	} else {
		echo '<div class="wrap"><h1>Configuration</h1><p>File not found.</p></div>';
	}
}
// END Render Settings Page

// Render Style Guide Page
function athena_user_guide_page() {
	if (!current_user_can('manage_options')) {
		return;
	}

	$file = dirname(__DIR__) . '/src/Views/user-guide-view.php';
	if (file_exists($file)) {
		include $file;
	} else {
		echo '<div class="wrap"><h1>User Guide</h1><p>File not found.</p></div>';
	}
}
// END Render About Us Page

// Render About Us Page
function athena_about_us_page() {
	if (!current_user_can('manage_options')) {
		return;
	}

	$file = dirname(__DIR__) . '/src/Views/about-us-view.php';
	if (file_exists($file)) {
		include $file;
	} else {
		echo '<div class="wrap"><h1>About Us</h1><p>File not found.</p></div>';
	}
}
// END Render About Us Page

// Render Help & Sypport Page
function athena_help_and_support_page() {
	if (!current_user_can('manage_options')) {
		return;
	}

	$file = dirname(__DIR__) . '/src/Views/help-and-support-view.php';
	if (file_exists($file)) {
		include $file;
	} else {
		echo '<div class="wrap"><h1>Help and Support</h1><p>File not found.</p></div>';
	}
}
// END Render Help & Sypport Page

// Full Reindex - WP Cron System
add_action('wp_ajax_athena_full_reindex_action', 'athena_full_reindex_ajax');
function athena_full_reindex_ajax() {
	if (!current_user_can('manage_options')) {
		wp_send_json_error('You do not have access rights.');
	}

	check_admin_referer('athena_full_reindex', 'athena_full_reindex_nonce');

	$reindexStatus = get_option('athena_reindex_status', []);
	if (!empty($reindexStatus['running'])) {
		wp_send_json_error('Reindex already in progress');
	}

	// Calculate total items to sync for accurate progress bar
	if (!class_exists('FullReindexController')) {
		require_once ASWP_ATHENA_CORE_INC . 'Controller/FullReindexController.php';
	}
	$fullReindexController = new FullReindexController();
	$total_items = $fullReindexController->calculateTotalItemsToSync();

	// Delete old log file if it exists
	$upload_dir = wp_upload_dir();
	$log_file = trailingslashit($upload_dir['basedir']) . 'athena/athena-reindex.log';
	if (file_exists($log_file)) {
		file_put_contents($log_file, '');
	}

	// Initialize status
	update_option('athena_reindex_status', [
		'running' => true,
		'step' => 'brands_manufacturers',
		'offset' => 0,
		'batch_size' => 500,
		'total_items_to_sync' => $total_items,
		'total_items_synced' => 0,
		'progress_percentage' => 0,
		'total_products' => 0,
		'last_error' => null,
		'started_at' => current_time('mysql'),
	]);

	// Schedule first step
	wp_schedule_single_event(time() + 1, 'athena_reindex_step_hook', [['step' => 'brands_manufacturers']]);

	// Runs wp cron immediately, doesn't wait for visits
	spawn_cron();

	wp_send_json_success('Reindex started successfully!');
}

add_action('wp_ajax_athena_stop_reindex_action', 'athena_stop_reindex_ajax');
function athena_stop_reindex_ajax() {
	if (!current_user_can('manage_options')) {
		wp_send_json_error('You do not have access rights.');
	}

	check_admin_referer('athena_full_reindex', 'athena_stop_reindex_nonce');

	$reindexStatus = get_option('athena_reindex_status', []);
	if (empty($reindexStatus['running'])) {
		wp_send_json_error('Reindex is not currently running.');
	}

	// Update status to stopped
	$reindexStatus['running'] = false;
	$reindexStatus['last_error'] = 'Stopped manually by user.';
	update_option('athena_reindex_status', $reindexStatus);

	// Clear scheduled cron hooks
	wp_clear_scheduled_hook('athena_reindex_step_hook');

	// Log the manual cancellation
	if (!class_exists('AthenaLogger')) {
		require_once ASWP_ATHENA_CORE_INC . 'Helpers/Logger.php';
	}
	AthenaLogger::reindexLogs('Reindex stopped manually by user.', 'error');
	AthenaLogger::info('Reindex stopped manually by user.');

	wp_send_json_success(['message' => 'Reindex stopped successfully.']);
}

add_action('athena_reindex_step_hook', 'athena_handle_reindex_step', 10, 1);
function athena_handle_reindex_step($args) {
	if (!is_array($args) || empty($args['step'])) return;

	if (!class_exists('FullReindexController')) {
		require_once ASWP_ATHENA_CORE_INC . 'Controller/FullReindexController.php';
	}

	try {
		$fullReindexController = new FullReindexController();
		$fullReindexController->runStep($args['step'], $args);
	} catch (Exception $e) {
		$reindexStatus = get_option('athena_reindex_status', []);
		$reindexStatus['running'] = false;
		$reindexStatus['last_error'] = $e->getMessage();
		update_option('athena_reindex_status', $reindexStatus);
		wp_clear_scheduled_hook('athena_reindex_step_hook');
		AthenaLogger::error('Reindex failed: ' . $e->getMessage());
	}
}

add_action('wp_ajax_athena_check_reindex_status', function() {
	$reindexStatus = get_option('athena_reindex_status', []);
	$running = !empty($reindexStatus['running']);
	$percentage = isset($reindexStatus['progress_percentage']) ? (int) $reindexStatus['progress_percentage'] : 0;

	// Offset-based log reading: JS sends how many lines it already has
	$last_line_count = isset($_GET['last_line_count']) ? (int) $_GET['last_line_count'] : 0;

	// Read latest logs
	$log_lines = [];
	$total_lines = 0;
	$upload_dir = wp_upload_dir();
	$log_file = trailingslashit($upload_dir['basedir']) . 'athena/athena-reindex.log';

	if (file_exists($log_file) && is_readable($log_file)) {
		$lines = file($log_file);
		if ($lines !== false) {
			$total_lines = count($lines);
			// Send only new lines since last poll
			$new_lines = array_slice($lines, $last_line_count);
			$log_lines = array_map('trim', $new_lines);
		}
	}

	wp_send_json([
		'in_progress' => $running,
		'progress_percentage' => $percentage,
		'log_lines' => $log_lines,
		'total_lines' => $total_lines,
		'is_reindex_successful' => $running ? null : (empty($reindexStatus['last_error']) ? 'success' : 'failed')
	]);
});

function athena_is_reindex_in_progress() {
	$reindexStatus = get_option('athena_reindex_status', []);
	return !empty($reindexStatus['running']);
}

add_action('athena_reset_reindex_status', function() {
	update_option('athena_reindex_status', ['running' => false]);
	wp_clear_scheduled_hook('athena_reindex_step_hook');
});
// END Full Reindex - WP Cron System

// Product Partial Reindex - Update Product
add_action('woocommerce_update_product', function ($product_id) {
	if (!$product_id) return;

	$productPartialReindexController = new ProductPartialReindexController();
	$productPartialReindexController->reindexProductUpdate($product_id);
});
// END Product Partial Reindex - Update Product

// Product Partial Reindex - Delete Product
add_action('wp_trash_post', function($product_id) {
	if (get_post_type($product_id) !== 'product') return;

	$productPartialReindexController = new ProductPartialReindexController();
	$productPartialReindexController->reindexProductDelete($product_id);
});
// END Product Partial Reindex - Delete Product

// After activating the plugin
register_activation_hook(dirname(__DIR__) . '/athena-search.php', function() {
	$options = get_option('athena_options', []);

	// Generate integration key if it doesn't exist
	if (empty($options['integration_key'])) {
		$options['integration_key'] = 'athena_' . bin2hex(random_bytes(20));
		update_option('athena_options', $options);
		$options = get_option('athena_options', []);
	}
	// END Generate integration key if it doesn't exist

	// Reset reindex status on plugin activation
	$reindex_status = get_option('athena_reindex_status', []);
	if (!empty($reindex_status) && $reindex_status['running'] == 'true') {
		$reindex_status['running'] = false;
		update_option('athena_reindex_status', $reindex_status);
		wp_clear_scheduled_hook('athena_reindex_step_hook');
	}
	// END Reset reindex status on plugin activation

	// Creating an Athena page with the content of our shortcode, or if the page already exists, update the option.
	$saved_page_id = intval($options['athena_landing_page'] ?? 0);

	if ($saved_page_id && get_post($saved_page_id)) {
		flush_rewrite_rules(true);
		return;
	}

	$page = get_page_by_path('athena');

	if (!$page) {
		$page_id = wp_insert_post([
			'post_title' => 'Athena',
			'post_name' => 'athena',
			'post_content' => '[athena_search_results]',
			'post_status' => 'publish',
			'post_type' => 'page'
		]);
	} else {
		$page_id = $page->ID;

		$content = get_post_field('post_content', $page_id);
		if (strpos($content, '[athena_search_results]') === false) {
			wp_update_post([
				'ID' => $page_id,
				'post_content' => $content . "\n[athena_search_results]"
			]);
		}
	}

	if ($page_id) {
		$options['athena_landing_page'] = $page_id;
		update_option('athena_options', $options);
		flush_rewrite_rules(true);
	}
	// END Creating an Athena page with the content of our shortcode, or if the page already exists, update the option.
});
// END After activating the plugin

// Remove the trailing slash only for /athena or any other slug under that id
add_filter('user_trailingslashit', function($url, $type = '', $original_url = '') {
	if (is_admin()) {
		return $url;
	}

	$options = get_option('athena_options', []);
	$page_id = intval($options['athena_landing_page'] ?? 0);
	if ($page_id) {
		$post = get_post($page_id);
		if ($post && $post->post_name) {
			$slug = $post->post_name;
			if (strpos($url, '/' . $slug . '/') !== false) {
				$url = rtrim($url, '/');
			}
		}
	}

	return $url;
}, 10, 3);
// END Remove the trailing slash only for /athena or any other slug under that id

// Cart Analytics - Track Add to Cart with Attribution
add_action('woocommerce_add_to_cart', function ($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
	$source = '';
	$channel = '';

	// Read attribution from Cookie (set by JavaScript)
	if (isset($_COOKIE['_athena_last_attr'])) {
		$attr = json_decode(stripslashes($_COOKIE['_athena_last_attr']), true);
		if ($attr) {
			$source = sanitize_text_field($attr['source'] ?? '');
			$channel = sanitize_text_field($attr['channel'] ?? '');
		}
	}

	// Immediate API Tracking
	if (class_exists('CartAnalyticsController')) {
		$cartAnalyticsController = new CartAnalyticsController();
		$cartAnalyticsController->trackAddToCart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data, $source, $channel);
	}
}, 10, 6);

/**
 * Capture attribution data and store it IN the cart item itself.
 * This ensures that if Product A is added via Voice and Product B via search,
 * each maintains its own source.
 */
add_filter('woocommerce_add_cart_item_data', function ($cart_item_data, $product_id, $variation_id) {
	if (isset($_COOKIE['_athena_last_attr'])) {
		$attr = json_decode(stripslashes($_COOKIE['_athena_last_attr']), true);
		if ($attr) {
			$cart_item_data['athena_attribution'] = [
				'source' => sanitize_text_field($attr['source'] ?? ''),
				'channel' => sanitize_text_field($attr['channel'] ?? ''),
				'timestamp' => time()
			];
		}
	}
	return $cart_item_data;
}, 10, 3);

/**
 * Transfer attribution from Cart Item into Order Item Meta during checkout
 */
add_action('woocommerce_checkout_create_order_line_item', function ($item, $cart_item_key, $values, $order) {
	if (isset($values['athena_attribution'])) {
		$attr = $values['athena_attribution'];
		$item->add_meta_data('_athena_source', $attr['source']);
		$item->add_meta_data('_athena_channel', $attr['channel']);
	}
}, 10, 4);
// END Cart Analytics

// Order Analytics - Track Purchase with Attribution
add_action('woocommerce_thankyou', function ($order_id) {
	// Send Order Analytics
	// We no longer pass global source/channel here because the controller
	// will now read it from each individual item's metadata.
	if (class_exists('OrderAnalyticsController')) {
		$orderAnalyticsController = new OrderAnalyticsController();
		$orderAnalyticsController->trackOrder($order_id);
	}
});
// END Order Analytics