<?php

/**
 * Compatibility helpers for reading order data whether HPOS or the legacy posts table is in use.
 *
 * @link       https://nudgesells.com
 * @since      1.0.0
 *
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 */

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

/**
 * NudgeSells_Order_Compat
 *
 * Provides the table/column names and status list Analytics and Suggestions queries need, adapted to HPOS or legacy storage.
 *
 * @since      1.0.0
 * @package    NudgeSells
 * @subpackage NudgeSells/includes
 * @author     NudgeSells <support@nudgesells.com>
 */
class NudgeSells_Order_Compat
{

	/**
	 * Hpos enabled.
	 *
	 * @return mixed
	 * @since 1.0.0
	 */
	public static function hpos_enabled()
	{
		return class_exists('\Automattic\WooCommerce\Utilities\OrderUtil')
			&& \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
	}

	/**
	 * Parts.
	 *
	 * @return array
	 * @since 1.0.0
	 */
	public static function parts()
	{
		global $wpdb;

		if (self::hpos_enabled()) {
			return array(
				'table'      => $wpdb->prefix . 'wc_orders',
				'id_col'     => 'id',
				'status_col' => 'status',
				'date_col'   => 'date_created_gmt',
				'statuses'   => array('wc-completed', 'wc-processing'),
			);
		}

		return array(
			'table'      => $wpdb->posts,
			'id_col'     => 'ID',
			'status_col' => 'post_status',
			'date_col'   => 'post_date_gmt',
			'statuses'   => array('wc-completed', 'wc-processing'),
		);
	}

	/**
	 * Status in clause.
	 *
	 * @return mixed
	 * @since 1.0.0
	 */
	public static function status_in_clause()
	{
		$parts = self::parts();
		return "'" . implode("','", array_map('esc_sql', $parts['statuses'])) . "'";
	}
}
