<?php

namespace WDevs\CustomerOrderExport;

/**
 * Handles variables for the Customer Order Export for WooCommerce plugin.
 *
 * This class provides methods to retrieve various variables that can be used
 * in notifications, including document titles, post titles, site names, and
 * WooCommerce-specific data when available.
 *
 * @since      1.0.0
 * @package    Wdevs_Customer_Order_Export
 * @subpackage Wdevs_Customer_Order_Export/includes
 * @author     Wijnberg Developments <contact@wijnberg.dev>
 */
class Variables {

	/**
	 * Retrieves all available variables with their labels and values.
	 *
	 * @param int|null $order_id The WooCommerce order ID
	 * @return array An associative array of variables with their labels and values
	 * @since 1.0.0
	 */
	public static function get_variables($order_id = null) {
		$variables = array(
			'order_id' => array(
				'label' => __('Order ID', 'orderbridge-for-woocommerce'),
				'value' => $order_id ?? '',
			),
			'date' => array(
				'label' => __('Date', 'orderbridge-for-woocommerce'),
				'value' => self::get_sanitized_date($order_id, 'date_format'),
			),
			'time' => array(
				'label' => __('Time', 'orderbridge-for-woocommerce'),
				'value' => self::get_sanitized_date($order_id, 'time_format'),
			),
		);

		uasort($variables, function($a, $b) {
			return strcmp($a['label'], $b['label']);
		});

		return apply_filters('wdevs_coe_get_variables', $variables);
	}

	/**
	 * Gets sanitized date or time from order
	 *
	 * @param int|null $order_id The WooCommerce order ID
	 * @param string $format_type Either 'date_format' or 'time_format'
	 * @return string Sanitized date/time string or empty string if not available
	 * @since 1.0.0
	 */
	private static function get_sanitized_date($order_id, $format_type) {
		if (!$order_id) {
			return '';
		}

		$order = wc_get_order($order_id);
		if (!$order) {
			return '';
		}

		$format = get_option($format_type);
		$raw_date = $order->get_date_created()->date_i18n($format);

		// Remove characters except numbers, letters, - and _
		$safe_date = preg_replace('/[^a-zA-Z0-9_-]/', '-', $raw_date);

		// Remove multiple consecutive hyphens
		$safe_date = preg_replace('/-+/', '-', $safe_date);

		// Trim hyphens from beginning and end
		return trim($safe_date, '-') ?: '';
	}
}