<?php
/**
 * Order Status Mapper Utility
 *
 * Maps Amazon order statuses to WooCommerce order statuses with
 * support for customization via WordPress filters.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/utils
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Utils;

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

/**
 * Class for mapping Amazon order statuses to WooCommerce order statuses.
 *
 * Provides a default mapping with filter hooks for customization.
 */
class Order_Status_Mapper {

	/**
	 * Get the default status mapping from Amazon to WooCommerce.
	 *
	 * Amazon Order Status values:
	 * - Pending: Order placed but not yet shipped
	 * - Unshipped: Order confirmed but not yet shipped
	 * - PartiallyShipped: Some items shipped, others pending
	 * - Shipped: All items shipped
	 * - Canceled: Order canceled
	 * - Unfulfillable: Order cannot be fulfilled
	 * - InvoiceUnconfirmed: Invoice pending confirmation
	 * - PendingAvailability: Waiting for item availability
	 *
	 * WooCommerce Order Status values:
	 * - pending: Payment pending
	 * - processing: Payment received, order being processed
	 * - on-hold: Order on hold awaiting action
	 * - completed: Order fulfilled
	 * - cancelled: Order cancelled
	 * - refunded: Order refunded
	 * - failed: Payment failed
	 *
	 * @return array<string, string> Mapping array with Amazon status as key and WooCommerce status as value.
	 */
	private static function get_default_status_map(): array {
		return array(
			'Pending'             => 'pending',
			'Unshipped'           => 'processing',
			'PartiallyShipped'    => 'processing',
			'Shipped'             => 'completed',
			'Canceled'            => 'cancelled',
			'Unfulfillable'       => 'failed',
			'InvoiceUnconfirmed'  => 'on-hold',
			'PendingAvailability' => 'on-hold',
		);
	}

	/**
	 * Map Amazon order status to WooCommerce order status.
	 *
	 * This method provides two levels of customization:
	 * 1. Filter the entire mapping array using 'momcs_amazon_to_woocommerce_status_map'
	 * 2. Filter individual mapped status using 'momcs_mapped_order_status'
	 *
	 * Example usage for customizing the entire map:
	 * ```php
	 * add_filter('momcs_amazon_to_woocommerce_status_map', function($map) {
	 *     $map['Shipped'] = 'processing'; // Change shipped orders to processing
	 *     return $map;
	 * });
	 * ```
	 *
	 * Example usage for individual order status override:
	 * ```php
	 * add_filter('momcs_mapped_order_status', function($wc_status, $amazon_status, $order_data) {
	 *     // Custom logic based on order data
	 *     if ($amazon_status === 'Shipped' && isset($order_data['FulfillmentChannel'])
	 *         && $order_data['FulfillmentChannel'] === 'MFN') {
	 *         return 'processing';
	 *     }
	 *     return $wc_status;
	 * }, 10, 3);
	 * ```
	 *
	 * @param string $amazon_status The Amazon order status.
	 * @param array  $order_data Optional. Complete Amazon order data for context in filters.
	 * @return string The mapped WooCommerce order status (without 'wc-' prefix).
	 */
	public static function map_amazon_status_to_woocommerce( string $amazon_status, array $order_data = array() ): string {
		// Get the default mapping.
		$status_map = self::get_default_status_map();

		/**
		 * Filter the Amazon to WooCommerce status mapping array.
		 *
		 * Allows developers to customize the entire mapping array.
		 *
		 * @since 1.0.0
		 *
		 * @param array<string, string> $status_map The default status mapping array.
		 */
		$status_map = apply_filters( 'momcs_amazon_to_woocommerce_status_map', $status_map );

		// Get mapped status or default to 'processing' for unknown statuses.
		$wc_status = $status_map[ $amazon_status ] ?? 'processing';

		/**
		 * Filter the mapped WooCommerce order status for a specific Amazon order.
		 *
		 * Allows developers to override the status mapping for individual orders
		 * based on Amazon status and order data context.
		 *
		 * @since 1.0.0
		 *
		 * @param string $wc_status     The mapped WooCommerce status.
		 * @param string $amazon_status The original Amazon order status.
		 * @param array  $order_data    Complete Amazon order data for context.
		 */
		$wc_status = apply_filters( 'momcs_mapped_order_status', $wc_status, $amazon_status, $order_data );

		// Ensure we return a valid WooCommerce status.
		$valid_statuses = array_keys( wc_get_order_statuses() );

		// Remove 'wc-' prefix from valid statuses for comparison.
		$valid_statuses = array_map(
			function ( $status ) {
				return str_replace( 'wc-', '', $status );
			},
			$valid_statuses
		);

		// If the filtered status is not valid, fall back to 'processing'.
		if ( ! in_array( $wc_status, $valid_statuses, true ) ) {
			$wc_status = 'processing';
		}

		return $wc_status;
	}

	/**
	 * Get all supported Amazon order statuses.
	 *
	 * @return array<string> List of Amazon order statuses.
	 */
	public static function get_supported_amazon_statuses(): array {
		return array_keys( self::get_default_status_map() );
	}

	/**
	 * Check if an Amazon status is supported in the default mapping.
	 *
	 * @param string $amazon_status The Amazon order status to check.
	 * @return bool True if supported, false otherwise.
	 */
	public static function is_supported_status( string $amazon_status ): bool {
		$status_map = self::get_default_status_map();
		return isset( $status_map[ $amazon_status ] );
	}
}
