<?php

if (!defined('WPINC')) {
	die;
}

class OrderAnalyticsController
{

	public function trackOrder($order_id)
	{
		$options = get_option('athena_options', []);
		$token = $options['dashboard_website_token'] ?? '';

		if (empty($token)) {
			AthenaLogger::error('Order Analytics: Missing Dashboard Website Token');
			return;
		}

		$order = wc_get_order($order_id);
		if (!$order) {
			AthenaLogger::error('Order Analytics: Order not found ID ' . $order_id);
			return;
		}

		// Prevent duplicate tracking
		if (get_post_meta($order_id, '_athena_analytics_sent', true)) {
			return;
		}
		update_post_meta($order_id, '_athena_analytics_sent', 'yes');

		// Prepare items
		$itemsData = [];
		foreach ($order->get_items() as $item_id => $item) {
			$product = $item->get_product();
			$itemsData[] = [
				'name' => $item->get_name(),
				'id' => $item->get_product_id(),
				'sku' => $product ? $product->get_sku() : '',
				'type' => $product ? $product->get_type() : '',
				'qty' => $item->get_quantity(),
				'price_incl_tax' => (float) $order->get_item_total($item, true),
				'price_with_qty_incl_tax' => (float) $order->get_line_total($item, true),
				'price' => (float) $order->get_item_total($item, false),
				'row_total' => (float) $order->get_line_total($item, false),
				'source' => $item->get_meta('_athena_source'),
				'channel' => $item->get_meta('_athena_channel'),
			];
		}

		$data = [
			'token' => $token,
			'ip_address' => $this->getIpAddress($order),
			'order' => [
				'quote_id' => $order_id,
				'increment_id' => $order->get_order_number(),
				'store_id' => get_current_blog_id(),
				'status' => $order->get_status(),
				'order_currency_code' => $order->get_currency(),
				'base_grand_total' => (float) $order->get_total(),
				'subtotal_price' => (float) $order->get_subtotal(),
				'tax_price' => (float) $order->get_total_tax(),
				'discount_price' => (float) $order->get_discount_total(),
				'shipping_price' => (float) $order->get_shipping_total() ?? 0,
				'items' => $itemsData
			]
		];

		$resp = authorized_fetch('conversion/order', $data);

		if (is_wp_error($resp)) {
			AthenaLogger::error('Order Analytics API Error: ' . $resp->get_error_message());
		}
	}

	private function getIpAddress($order = null)
	{
		if ($order) {
			$ip = $order->get_customer_ip_address();
			if (!empty($ip)) {
				return $ip;
			}
		}

		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			return $_SERVER['HTTP_CLIENT_IP'];
		} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			return $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			return $_SERVER['REMOTE_ADDR'] ?? '';
		}
	}
}