<?php
/**
 * Class AP_Status_Controller file.
 *
 * @package Addonpayments
 */

use ComerciaGlobalPayments\AddonPayments\SDK\Response\OperationInterface;
use ComerciaGlobalPayments\AddonPayments\SDK\Response\Transaction;
use WooCommerce\Plugin\AddonPayments\Operations\ProcessTransaction;
use WooCommerce\Plugin\AddonPayments\Operations\ValidateOrder;

defined( 'ABSPATH' ) || exit;

/**
 * Status Controller
 */
class AP_Status_Controller {

	/**
	 * Process status request from EPG.
	 *
	 * @param int    $order_id \WooCommerce Order ID.
	 * @param string $trx merchant transaction ID.
	 *
	 * @return void
	 * @throws \Exception Exception.
	 */
	public function __invoke( $order_id, $trx ) {

		$payload = $this->get_payload();
		$order   = new WC_Order( $order_id );

		$operations =
			isset( $payload->{OperationInterface::RESPONSE_OPERATIONS_KEY} ) ?
				OperationInterface::RESPONSE_OPERATIONS_KEY :
				OperationInterface::RESPONSE_OPERATIONS_ARRAY_KEY;

		if ( is_object( $payload->{$operations} )
		     && is_array( $payload->{$operations}->operation ) ) {
			$payload->{$operations} = $payload->{$operations}->operation;

		} elseif ( is_object( $payload->{$operations} )
		           && is_object( $payload->{$operations}->operation ) ) {
			$payload->{$operations} = (array) $payload->{$operations};
		}


		if ( property_exists( $payload, 'status' )
		     && ( OperationInterface::STATUS_ERROR === $payload->status
		          || OperationInterface::STATUS_FAIL === $payload->status )
		) {
			if( $order->get_status() !== WC_Gateway_EasyPaymentGateway::ORDER_FAILED) {
				$message = property_exists($payload->message) ?
					$payload->message : __( 'Payment error', 'addonpayments' );
				$order->update_status(
					WC_Gateway_EasyPaymentGateway::ORDER_FAILED,
					$message);
			}

			exit;
		}

		if ( empty( $payload->{$operations} ) ) {
			throw new Exception( 'The request does not contain any operations.' );
		}

		$transactions = array();
		$n_operations = count( $payload->operations );

		$sorted = 1;
		foreach ( $payload->operations as $operation ) {
			$transaction = new Transaction( $operation, $sorted );

			( new ProcessTransaction() )(
				$transaction,
				$n_operations,
				$order_id
			);
			$transactions[] = $transaction;
			++$sorted;
		}

		try {
			( new ValidateOrder() )( $transactions, $order );

		} catch ( Exception $e ) {
			throw new Exception( $e->getMessage() );
		}

	}

	/**
	 * Get request payload
	 *
	 * @return false|string
	 */
	private function get_payload() {
		$payload = file_get_contents( 'php://input' );
		$payload = preg_replace(
			array( '/\n/', '/\t/', '/' . PHP_EOL . '/' ),
			'',
			$payload
		);

		if ( wp_is_json_request() ) {
			$payload = json_decode( $payload, false );
		} else {
			$payload =
				json_decode(
					wp_json_encode( simplexml_load_string( $payload ) ),
					false
				);
		}

		return $payload;
	}

}
