<?php
/**
 * Amazon Fulfillment Status Meta Box View
 *
 * Renders outbound Amazon fulfillment status and retry actions on order edit.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/views/src/common/pages/orders
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Views\Src\Common\Pages\Orders;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Plans\Premium\Services\Order_Fulfillment_Channel_Resolver;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Renders Amazon fulfillment status panel.
 */
class Amazon_Fulfillment_Status_Metabox_View {

	/**
	 * Channel resolver.
	 *
	 * @var Order_Fulfillment_Channel_Resolver
	 */
	private Order_Fulfillment_Channel_Resolver $channel_resolver;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->channel_resolver = new Order_Fulfillment_Channel_Resolver();
	}

	/**
	 * Render metabox content.
	 *
	 * @param int $order_id WooCommerce order ID.
	 * @return void
	 */
	public function render( int $order_id ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			echo '<p>' . esc_html__( 'Order not found.', 'multi-channel-for-woocommerce' ) . '</p>';
			return;
		}

		$state          = $order->get_meta( Plugin_Constants::ORDER_META_AMAZON_FULFILLMENT );
		$state          = is_array( $state ) ? $state : array();
		$failed_count   = 0;
		$enabled_channels = $this->channel_resolver->get_enabled_channels();

		?>
		<div class="momcs-fulfillment-status-metabox">
			<p>
				<?php esc_html_e( 'This section shows automatic Amazon fulfillment attempts for this WooCommerce order.', 'multi-channel-for-woocommerce' ); ?>
			</p>

			<?php if ( empty( $enabled_channels ) && empty( $state ) ) : ?>
				<div class="notice notice-info inline">
					<p><?php esc_html_e( 'No channels currently have automatic order fulfillment enabled.', 'multi-channel-for-woocommerce' ); ?></p>
				</div>
			<?php endif; ?>

			<table class="widefat striped momcs-fulfillment-status-table">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Channel', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Status', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Fulfillment ID', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Attempts', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Last Attempt', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Last Error', 'multi-channel-for-woocommerce' ); ?></th>
						<th><?php esc_html_e( 'Action', 'multi-channel-for-woocommerce' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php
					$rendered = array();

					foreach ( $state as $channel_uuid => $channel_state ) :
						if ( ! is_array( $channel_state ) ) {
							continue;
						}
						$rendered[ $channel_uuid ] = true;
						$failed_count += ( 'failed' === (string) ( $channel_state['status'] ?? '' ) ) ? 1 : 0;
						$this->render_row( (string) $channel_uuid, $channel_state );
					endforeach;

					foreach ( $enabled_channels as $channel ) :
						$channel_uuid = (string) ( $channel['uuid'] ?? '' );
						if ( '' === $channel_uuid || isset( $rendered[ $channel_uuid ] ) ) {
							continue;
						}
						$this->render_row(
							$channel_uuid,
							array(
								'channel_name' => (string) ( $channel['connection_name'] ?? $channel_uuid ),
								'status'       => 'not_queued',
							)
						);
					endforeach;

					if ( empty( $state ) && empty( $enabled_channels ) ) :
						?>
						<tr>
							<td colspan="7"><?php esc_html_e( 'No fulfillment data found.', 'multi-channel-for-woocommerce' ); ?></td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>

			<div class="momcs-fulfillment-actions">
				<?php if ( $failed_count > 0 ) : ?>
					<button type="button" class="button button-primary momcs-fulfillment-retry-all">
						<?php esc_html_e( 'Retry Failed Channels', 'multi-channel-for-woocommerce' ); ?>
					</button>
				<?php endif; ?>
				<span class="spinner"></span>
				<div class="momcs-fulfillment-message" style="display: none;"></div>
			</div>

			<input type="hidden" id="momcs-fulfillment-order-id" value="<?php echo esc_attr( $order_id ); ?>" />
			<input type="hidden" id="momcs-fulfillment-retry-nonce" value="<?php echo esc_attr( wp_create_nonce( 'momcs_order_fulfillment_retry_nonce' ) ); ?>" />
		</div>
		<?php
	}

	/**
	 * Render one channel status row.
	 *
	 * @param string $channel_uuid Channel UUID.
	 * @param array  $channel_state Per-channel state.
	 * @return void
	 */
	private function render_row( string $channel_uuid, array $channel_state ): void {
		$channel_name  = (string) ( $channel_state['channel_name'] ?? $channel_uuid );
		$status        = (string) ( $channel_state['status'] ?? 'not_queued' );
		$fulfillment_id = (string) ( $channel_state['fulfillment_order_id'] ?? '' );
		$attempts      = (int) ( $channel_state['attempt_count'] ?? 0 );
		$last_attempt  = (string) ( $channel_state['last_attempt_at'] ?? '' );
		$last_error    = (string) ( $channel_state['last_error'] ?? '' );
		$status_label  = $this->get_status_label( $status );
		$status_class  = sanitize_html_class( 'momcs-status-' . $status );
		?>
		<tr>
			<td><?php echo esc_html( $channel_name ); ?></td>
			<td><span class="momcs-status-pill <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span></td>
			<td><?php echo '' !== $fulfillment_id ? esc_html( $fulfillment_id ) : '&mdash;'; ?></td>
			<td><?php echo esc_html( (string) $attempts ); ?></td>
			<td><?php echo '' !== $last_attempt ? esc_html( $last_attempt ) : '&mdash;'; ?></td>
			<td><?php echo '' !== $last_error ? esc_html( $last_error ) : '&mdash;'; ?></td>
			<td>
				<?php if ( 'failed' === $status ) : ?>
					<button type="button" class="button momcs-fulfillment-retry-channel" data-channel-uuid="<?php echo esc_attr( $channel_uuid ); ?>">
						<?php esc_html_e( 'Retry', 'multi-channel-for-woocommerce' ); ?>
					</button>
				<?php else : ?>
					&mdash;
				<?php endif; ?>
			</td>
		</tr>
		<?php
	}

	/**
	 * Human-readable labels for channel statuses.
	 *
	 * @param string $status Channel status.
	 * @return string
	 */
	private function get_status_label( string $status ): string {
		$labels = array(
			'not_queued' => __( 'Not Queued', 'multi-channel-for-woocommerce' ),
			'queued'     => __( 'Queued', 'multi-channel-for-woocommerce' ),
			'processing' => __( 'Processing', 'multi-channel-for-woocommerce' ),
			'retrying'   => __( 'Retrying', 'multi-channel-for-woocommerce' ),
			'fulfilled'  => __( 'Fulfilled', 'multi-channel-for-woocommerce' ),
			'failed'     => __( 'Failed', 'multi-channel-for-woocommerce' ),
		);

		return $labels[ $status ] ?? ucfirst( $status );
	}
}

