<?php

/**
 * Stamps completed order line items with the offer that produced them, for later reporting.
 *
 * @link       https://nudgesells.com
 * @since      1.0.0
 *
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 */

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

/**
 * NudgeSells_Order_Tracking
 *
 * Records which offer (and, for Pro, which A/B test variant) a purchased add-on or upgrade line item came from.
 *
 * @since      1.0.0
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 * @author     NudgeSells <support@nudgesells.com>
 */
class NudgeSells_Order_Tracking
{

	/**
	 * Stamp line item.
	 *
	 * @param mixed $item
	 * @param mixed $cart_item_key
	 * @param mixed $values
	 * @param mixed $order
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function stamp_line_item($item, $cart_item_key, $values, $order)
	{
		if (empty($values['nudgesells_role'])) {
			return;
		}

		$role = $values['nudgesells_role'];
		$item->add_meta_data('_nudgesells_role', $role, true);

		if (! empty($values['nudgesells_group'])) {
			$item->add_meta_data('_nudgesells_group', $values['nudgesells_group'], true);
		}
		if (! empty($values['nudgesells_host_id'])) {
			$item->add_meta_data('_nudgesells_host_id', absint($values['nudgesells_host_id']), true);
		}

		$offer_id = 0;
		if (! empty($values['nudgesells_host_id'])) {
			$offer = NudgeSells_Offer_Repository::get_offer_for_product($values['nudgesells_host_id']);
			$offer_id = $offer ? $offer->ID : 0;
		}
		$item->add_meta_data('_nudgesells_offer_id', $offer_id, true);

		if ('host' === $role) {
			return;
		}

		$product      = $item->get_product();
		$regular_price = 0;
		if ($product) {
			$regular_price = $product->is_on_sale() ? (float) $product->get_sale_price() : (float) $product->get_regular_price();
			if (! $regular_price) {
				$regular_price = (float) $product->get_price();
			}
		}
		$qty        = max(1, (int) $item->get_quantity());
		$paid_total = (float) $item->get_total();

		$regular_unit_excl  = $product ? (float) wc_get_price_excluding_tax($product, array('qty' => 1, 'price' => $regular_price)) : 0;
		$saved              = max(0, ($regular_unit_excl * $qty) - $paid_total);

		$item->add_meta_data('_nudgesells_saved_amount', wc_format_decimal($saved, 2), true);
		$item->add_meta_data('_nudgesells_revenue_amount', wc_format_decimal($paid_total, 2), true);

		if ($product) {
			$regular_unit_incl = (float) wc_get_price_including_tax($product, array('qty' => 1, 'price' => $regular_price));
			$paid_total_incl   = $paid_total + (float) $item->get_total_tax();
			$display_saved     = max(0, ($regular_unit_incl * $qty) - $paid_total_incl);

			if ($display_saved > 0) {
				$item->add_meta_data(__('Discount applied', 'nudgesells'), wc_price(-$display_saved), true);
			}
		}

		do_action('nudgesells_conversion_recorded', $offer_id, $paid_total);
	}

	/**
	 * Hide order item meta.
	 *
	 * WooCommerce only auto-hides a fixed list of its own internal order
	 * item meta keys in the admin order screen - a leading underscore alone
	 * doesn't hide anything there (unlike post meta), so our own tracking
	 * keys would otherwise show up as raw meta rows to shop managers.
	 *
	 * @param array $hidden_meta_keys
	 *
	 * @return array
	 * @since 1.0.0
	 */
	public function hide_order_item_meta($hidden_meta_keys)
	{
		return array_merge($hidden_meta_keys, array(
			'_nudgesells_role',
			'_nudgesells_group',
			'_nudgesells_host_id',
			'_nudgesells_offer_id',
			'_nudgesells_saved_amount',
			'_nudgesells_revenue_amount',
		));
	}

	/**
	 * Flag order item name.
	 *
	 * Adds the same arrow-indent treatment used on the cart/checkout
	 * pages to add-on line items wherever an order's items table is
	 * rendered -- the Thank You page, My Account order view, and order
	 * emails all share this one filter. Inline styles are used rather
	 * than a CSS class, since emails can't reliably load an external
	 * stylesheet or resolve CSS custom properties. Upgrades are
	 * deliberately excluded, matching the cart/checkout treatment.
	 *
	 * @param string             $item_name
	 * @param WC_Order_Item|null $item
	 *
	 * @return string
	 * @since 1.0.0
	 */
	public function flag_order_item_name($item_name, $item = null)
	{
		if (! $item instanceof WC_Order_Item || 'addon' !== $item->get_meta('_nudgesells_role')) {
			return $item_name;
		}

		$accent = NudgeSells_Admin_Settings::get('color_accent', '#1E5F46');

		return sprintf(
			'<span style="display:inline-block;margin-right:6px;color:%1$s;font-weight:700;" aria-hidden="true">&#8627;</span>%2$s',
			esc_attr($accent),
			$item_name
		);
	}
}
