<?php
/**
 * Shipment Controller
 *
 * Handles AJAX requests for shipment confirmation.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers;

use MOMCS_Sync\Includes\Common\Handlers\Shipment_Handler;
use MOMCS_Sync\Includes\Common\Utils\Logger;

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

/**
 * Class for handling shipment controller operations.
 */
class Shipment_Controller {

	/**
	 * Shipment Handler instance.
	 *
	 * @var Shipment_Handler
	 */
	private $shipment_handler;

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	private $logger;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->shipment_handler = new Shipment_Handler();
		$this->logger           = new Logger( 'shipment-controller' );
	}

	/**
	 * Handle AJAX request to confirm shipment.
	 *
	 * @return void
	 */
	public function confirm_amazon_shipment(): void {
		try {
			// Verify nonce.
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'momcs_shipment_confirmation_nonce' ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'Security check failed.', 'multi-channel-for-woocommerce' ),
					),
					403
				);
				return;
			}

			// Check user permissions.
			if ( ! current_user_can( 'edit_shop_orders' ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'You do not have permission to perform this action.', 'multi-channel-for-woocommerce' ),
					),
					403
				);
				return;
			}

			// Get order ID.
			if ( ! isset( $_POST['order_id'] ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'Order ID is required.', 'multi-channel-for-woocommerce' ),
					),
					400
				);
				return;
			}

			$order_id = absint( $_POST['order_id'] );
			if ( $order_id <= 0 ) {
				wp_send_json_error(
					array(
						'message' => __( 'Invalid order ID.', 'multi-channel-for-woocommerce' ),
					),
					400
				);
				return;
			}

			// Get packages data.
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in sanitize_packages_data().
			if ( ! isset( $_POST['packages'] ) || ! is_array( wp_unslash( $_POST['packages'] ) ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'Package data is required.', 'multi-channel-for-woocommerce' ),
					),
					400
				);
				return;
			}

			// Sanitize packages data.
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized in sanitize_packages_data().
			$packages = $this->sanitize_packages_data( wp_unslash( $_POST['packages'] ) );

			if ( empty( $packages ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'No valid packages provided.', 'multi-channel-for-woocommerce' ),
					),
					400
				);
				return;
			}

			$this->logger->debug( "Received shipment confirmation request for order #{$order_id} with " . count( $packages ) . ' package(s)' );

			// Process shipment confirmation.
			$result = $this->shipment_handler->confirm_order_shipment( $order_id, $packages );

			if ( $result['success'] ) {
				wp_send_json_success(
					array(
						'message' => $result['message'],
					)
				);
			} else {
				wp_send_json_error(
					array(
						'message' => $result['message'],
					),
					400
				);
			}
		} catch ( \Exception $e ) {
			$this->logger->error( 'Exception in confirm_amazon_shipment: ' . $e->getMessage() );
			wp_send_json_error(
				array(
					'message' => __( 'An unexpected error occurred.', 'multi-channel-for-woocommerce' ),
				),
				500
			);
		}
	}

	/**
	 * Sanitize packages data from POST request.
	 *
	 * @param array $packages Raw packages data.
	 * @return array Sanitized packages data.
	 */
	private function sanitize_packages_data( array $packages ): array {
		$sanitized = array();

		foreach ( $packages as $package ) {
			if ( ! is_array( $package ) ) {
				continue;
			}

			$sanitized_package = array(
				'packageReferenceId' => isset( $package['packageReferenceId'] ) ? sanitize_text_field( $package['packageReferenceId'] ) : '',
				'carrierCode'        => isset( $package['carrierCode'] ) ? sanitize_text_field( $package['carrierCode'] ) : '',
				'carrierName'        => isset( $package['carrierName'] ) ? sanitize_text_field( $package['carrierName'] ) : '',
				'shippingMethod'     => isset( $package['shippingMethod'] ) ? sanitize_text_field( $package['shippingMethod'] ) : '',
				'trackingNumber'     => isset( $package['trackingNumber'] ) ? sanitize_text_field( $package['trackingNumber'] ) : '',
				'shipDate'           => isset( $package['shipDate'] ) ? sanitize_text_field( $package['shipDate'] ) : '',
				'orderItems'         => array(),
			);

			// Optional COD collection method.
			if ( isset( $package['codCollectionMethod'] ) ) {
				$sanitized_package['codCollectionMethod'] = sanitize_text_field( $package['codCollectionMethod'] );
			}

			// Sanitize order items.
			if ( isset( $package['orderItems'] ) && is_array( $package['orderItems'] ) ) {
				foreach ( $package['orderItems'] as $item ) {
					if ( ! is_array( $item ) || ! isset( $item['orderItemId'] ) || ! isset( $item['quantity'] ) ) {
						continue;
					}

					$sanitized_package['orderItems'][] = array(
						'orderItemId' => sanitize_text_field( $item['orderItemId'] ),
						'quantity'    => absint( $item['quantity'] ),
					);
				}
			}

			$sanitized[] = $sanitized_package;
		}

		return $sanitized;
	}
}
