<?php

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

class CartAnalyticsController {
	public function trackAddToCart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data, $source = '', $channel = '') {
		$options = get_option('athena_options', []);
		$token = $options['dashboard_website_token'] ?? '';

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

		$data = [
			'token' => $token,
			'oId' => (string) $product_id,
			'athenaUid' => $_COOKIE['_athena-uid'] ?? '',
			'source' => $source,
			'channel' => $channel,
			'ip_address' => $this->getIpAddress(),
		];

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

		if (is_wp_error($resp)) {
			throw new Exception('Cart Analytics API Error: ' . $resp->get_error_message());
		}
	}

	private function getIpAddress() {
		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'] ?? '';
		}
	}
}