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


use ComerciaGlobalPayments\AddonPayments\SDK\Api\EPGJs;
use ComerciaGlobalPayments\AddonPayments\SDK\Response\OperationInterface;
use WooCommerce\Plugin\AddonPayments\Entities\Transaction;
use WooCommerce\Plugin\AddonPayments\Operations\OrderRefund;

defined( 'ABSPATH' ) || exit;

/**
 * Callback Controller
 */
class AP_Quix_Refund {

	/**
	 * Addonpayments Gateway.
	 *
	 * @var \WC_Gateway_EasyPaymentGateway
	 */
	private $gateway;

	public function __construct() {
		add_action( 'init', array( $this, 'init' ) );
	}

	public function init() {
		$payment_gateways = WC()->payment_gateways()->get_available_payment_gateways();

		if ( ! isset( $payment_gateways[ ID_EPG ] ) ) {
			return;
		}

		$this->gateway = $payment_gateways[ ID_EPG ];

		add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
		add_action( 'wp_ajax_ap_quix_refund', array( $this, 'do_refund' ) );
		add_action( 'addonpayments_after_order_transactions', array( $this, 'add_cashier_div' ) );
	}

	public function admin_enqueue_scripts() {
		$screen = get_current_screen();

		if ( 'shop_order' === $screen->post_type && 'post' === $screen->base ) {
			$order_id       = get_the_id();
			$order          = wc_get_order( $order_id );
			$payment_method = $order->get_payment_method();
			$endpoints      = EPGJs::getEndpoints( 'yes' === $this->gateway->settings['live_mode'] );

			if ( $payment_method !== ID_EPG ) {
				return;
			}

			$transactions     = Transaction::getRefundableByOrder( $order_id );

			if( empty($transactions) ) {
				return;
			}

			$payment_solution = reset( $transactions )->paymentSolution;

			if ( $payment_solution === WC_Gateway_EasyPaymentGateway::BNPL_NAME
			     || $payment_solution === 'nemuru'
			) {

				wp_enqueue_script( 'nemuru-widget-js', esc_url( $endpoints['nemuru-widget'] ), array( 'jquery' ), ADDONPAYMENTS_VERSION, true );
				wp_enqueue_script( 'ap_refund', esc_url( plugins_url( 'assets' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'refund.js', ADDONPAYMENTS_PLUGIN_FILE ) ), array('nemuru-widget-js'), ADDONPAYMENTS_VERSION, true );

				wp_localize_script( 'ap_refund', 'addonpayments', array(
					'payment_solution' => $payment_solution,
					'button_text'      => __( 'Reembolsar mediante Addon Payments', 'addonpayments' ),
					'url'              => admin_url( 'admin-ajax.php' ),
					'action'           => 'ap_quix_refund',
					'nonce'            => wp_create_nonce( 'addonpayments-nonce' ),
					'order_id'         => $order_id,
					'base_url'         => $endpoints['base'],
					'callback'         => wc_get_current_admin_url(),
					'error_message'    => __('An error occurred', 'addonpayments')
				) );
			}
		}
	}

	public function add_cashier_div() {
		echo '<div id="epgjs-cashier-div"></div>';
	}

	/**
	 * @throws \Exception
	 */
	public function do_refund() {
		if ( ! isset( $_POST['nonce'] ) ) {
			wp_send_json_error( 'Ha ocurrido un error' );
		}

		if ( ! wp_verify_nonce( $_POST['nonce'], 'addonpayments-nonce' ) ) {
			wp_send_json_error( 'Ha ocurrido un error' );
		}

		$order_id = sanitize_key( $_POST['order_id'] );
		$response = ( new OrderRefund() )( $order_id, 0 );

		if ($response instanceof OperationInterface) {

			if( $response->hasFailed() ) {
				$message = $response->getTransaction()->getMessage();
				wp_send_json_error(['error' => $message]);
			}

			$transaction = $response->getTransaction();
			$details     = json_decode( $transaction->getDetails() );

			$transactionResponse = array(
				'locale'      => str_replace( '_', '-', get_user_locale() ),
				'currency'    => get_woocommerce_currency(),
				'orderId'     => $details->orderId,
				'accessToken' => $details->authToken,
				'clientId'    => $details->clientId,
			);

			wp_send_json_success( $transactionResponse );

		}

	}
}