<?php

namespace WooCommerce\Plugin\AddonPayments;

use WooCommerce\Plugin\AddonPayments\Entities\Transaction;

class ErrorController {

	public function __construct() {
		add_filter( 'query_vars', array( $this, 'query_vars' ) );
		add_action(
			'woocommerce_before_checkout_form',
			array(
				$this,
				'show_errors',
			)
		);
	}

	public function query_vars( $query_vars ) {
		$query_vars[] = 'epg_error';
		$query_vars[] = 'epg_cancel';

		return $query_vars;
	}

	public function show_errors() {
		$epg_error  = get_query_var( 'epg_error' );
		$epg_cancel = get_query_var( 'epg_cancel' );

		if ( $epg_error ) {
			$notice      = __( 'The payment has failed', 'addonpayments' );
			$transaction = $this->get_transaction( $epg_error );

			if ( ! empty( $transaction ) && 'ERROR' === $transaction->status ) {
				$notice = $transaction->message;
			}

			wc_add_notice( $notice, 'error' );
		}

		if ( $epg_cancel ) {
			$notice      = __( 'The payment has been cancelled', 'addonpayments' );
			$transaction = $this->get_transaction( $epg_cancel );

			if ( 'ERROR' === $transaction->status ) {
				$notice = $transaction->message;
			}

			wc_add_notice( $notice, 'error' );
		}
	}

	function get_transaction( $merchantTransactionId, $counter = 0 ) {
		$transactions = Transaction::getByMerchTransactionId( $merchantTransactionId );
		$transaction  = reset( $transactions );

		if ( empty( $transactions ) && $counter < 5 ) {
			sleep( 0.2 );
			$counter ++;
			$this->get_transaction( $merchantTransactionId, $counter );
		}

		return $transaction;
	}
}
