<?php
/**
 * Trait: Anet_Order_Meta
 *
 * Provides utility methods for handling order meta
 *
 * @package Authorize_Net_Payments_For_Woocommerce
 * @subpackage Authorize_Net_Payments_For_Woocommerce/includes
 */

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

trait Anet_Order_Meta
{
	/**
	 * Adds order meta data
	 *
	 * @param object $order order object.
	 * @param string $key meta key.
	 * @param string $value meta value.
	 * @param bool   $unique indicates whether the meta value should be unique.
	 *
	 * @return boolean
	 */
	public function add_order_meta($order, $key, $value, $unique = false)
	{
		if (is_numeric($order)) {
			$order = wc_get_order($order);
		}
		if ($order instanceof \WC_Order) {
			if (anet_handle_hpos_compatibility()) {
				$order->add_meta_data($key, $value, $unique);
				$order->save_meta_data();
			} else {
				add_post_meta($order->get_id(),  $key, $value);
			}
		}
		return $order instanceof \WC_Order;
	}
	/**
	 * Delete order meta data
	 *
	 * @param object $order order object.
	 * @param string $key meta key.
	 *
	 * @return boolean
	 */
	public function delete_order_meta($order, $key)
	{
		if (is_numeric($order)) {
			$order = wc_get_order($order);
		}
		if ($order instanceof \WC_Order) {
			if (anet_handle_hpos_compatibility()) {
				$order->delete_meta_data($key);
				$order->save_meta_data();
			} else {
				delete_post_meta($order->get_id(), $key);
			}
		}
		return $order instanceof \WC_Order;
	}
	/**
	 * Updates order meta.
	 *
	 * @param \WC_Order $order order details.
	 * @param string    $key array key.
	 * @param string    $value value.
	 *
	 * @return boolean
	 */
	public function update_order_meta($order, $key, $value)
	{
		if (is_numeric($order)) {
			$order = wc_get_order($order);
		}
		if ($order instanceof \WC_Order) {
			if (anet_handle_hpos_compatibility()) {
				$order->update_meta_data($key, $value);
				$order->save_meta_data();
			} else {
				update_post_meta($order->get_id(), $key, $value);
			}
		}
		return $order instanceof \WC_Order;
	}
	/**
	 * Provides order meta data.
	 *
	 * @param object $order order details.
	 * @param string $key key.
	 *
	 * @return array
	 */
	public function get_order_meta($order, $key)
	{
		$meta = array();
		if (is_numeric($order)) {
			$order = wc_get_order($order);
		}
		if ($order instanceof \WC_Order) {
			if (anet_handle_hpos_compatibility()) {
				$meta = $order->get_meta($key, true, 'edit');
			} else {
				$meta = get_post_meta($order->get_id(),  $key, true);
			}
		}
		return $meta;
	}
	/**
	 * Provides order meta data.
	 *
	 * @param object $order order details.
	 *
	 * @return array
	 */
	public function get_order_meta_data($order)
	{
		$meta = array();
		if (is_numeric($order)) {
			$order = wc_get_order($order);
		}
		if ($order instanceof \WC_Order) {
			if (anet_handle_hpos_compatibility()) {
				$meta = $order->get_meta_data();
			} else {
				$meta = get_post_meta($order->get_id());
			}
		}
		return $meta;
	}
}
