<?php


namespace WooCommerce\Plugin\AddonPayments\Operations;

use ComerciaGlobalPayments\AddonPayments\SDK\Encryption\Cypher\Aes256Ecb;

class ProcessTransaction {

	public function __invoke( $transaction, $operations, $idOrder ) {
		global $wpdb;
		$dbPrefix = $wpdb->prefix;
		$cypher   = new Aes256Ecb();

		try {
			// @TODO: Move this to the Entity Transaction
			$payfrexTxId  = $transaction->getPayFrexTransactionId();
			$merchantTxId = $transaction->getMerchantTransactionId();
			$sortedOrder  = $transaction->getSortedOrder();

			$exists = $wpdb->get_var(
				"SELECT `id_epg_transaction`
                FROM `{$dbPrefix}epg_transaction`
                WHERE `payFrexTransactionId` = '$payfrexTxId'
                AND `merchantTransactionId` = '$merchantTxId'
                AND `sortedOrder` = {$sortedOrder}"
			);

			$values = array(
				'payFrexTransactionId'         => $payfrexTxId,
				'merchantTransactionId'        => $merchantTxId,
				'sortedOrder'                  => $sortedOrder,
				'EPGTransactionID'             => $transaction->getEPGTransactionID(),
				'amount'                       => $transaction->getAmount(),
				'currency'                     => $transaction->getCurrency(),
				'originalPayfrexTransactionId' => $transaction->getOriginalPayFrexTransactionId(),
				'originalAmount'               => $transaction->getOriginalAmount(),
				'originalCurrency'             => $transaction->getOriginalCurrency(),
				'remainingAmount'              => $transaction->getRemainingAmount(),
				'fee'                          => $transaction->getFee(),
				'details'                      => $cypher->encrypt( json_encode( $transaction->getDetails() ), SECURE_AUTH_KEY ),
				'message'                      => $transaction->getMessage(),
				'operationType'                => $transaction->getOperationType(),
				'paymentDetails'               => $cypher->encrypt( json_encode( $transaction->getPaymentDetails() ), SECURE_AUTH_KEY ),
				'optionalTransactionParams'    => json_encode( $transaction->getOptionalTransactionParams() ),
				'paymentSolution'              => $transaction->getPaymentSolution(),
				'paySolTransactionId'          => $transaction->getPaySolTransactionId(),
				'respCode'                     => json_encode( $transaction->getRespCode() ),
				'status'                       => $transaction->getStatus(),
				'lastOp'                       => $transaction->getSortedOrder() === $operations,
				'rawData'                      => $cypher->encrypt( json_encode( $transaction->getRawTransactionObject() ), SECURE_AUTH_KEY ),
				'updatedAt'                    => date( 'Y-m-d H:i:s' ),
			);

			if ( ! $exists ) {
				$values += array(
					'id_order'  => $idOrder,
					'createdAt' => date( 'Y-m-d H:i:s' ),
				);

				$result = $wpdb->insert( $dbPrefix . 'epg_transaction', $values );

				if ( false === $result ) {
					throw new \RuntimeException( 'The transaction was not stored in the database' );
				}

				return;
			}

			$result = $wpdb->update(
				$dbPrefix . 'epg_transaction',
				$values,
				array( 'id_epg_transaction' => $exists )
			);

			if ( false === $result ) {
				throw new \RuntimeException( 'The transaction was not stored in the database' );
			}
		} catch ( \Exception $e ) {
			error_log(
				$e->getMessage() . PHP_EOL . $e->getCode() . PHP_EOL,
				3,
				plugin_dir_path( __FILE__ ) . 'debug.log'
			);
		}
	}
}
