<?php
/**
 * This file handles Payment Gateway Core Action
 *
 * @package WkwcAdyen
 * @version 1.2.0
 */
namespace WkwcAdyen\Includes;

defined( 'ABSPATH' ) || exit; // Exit if access directly.

use WC_Order;
use WC_Payment_Gateways;
use Adyen\Util\HmacSignature;

use WkwcAdyen\Helper\Common;

use WkwcAdyen\Helper\Adyen\Wkwc_Adyen_Helper;
use WkwcAdyen\Helper\Adyen\Notifications\Wkwc_Abstract_Handler;
use WkwcAdyen\Helper\Adyen\Notifications\Wkwc_Handlers_Factory;
use WkwcAdyen\Helper\Adyen\Notifications\DataObjects\Wkwc_Adyen_Notification_Request;
use WkwcAdyen\Includes\Payment_Methods;
use WkwcAdyen\Templates\Admin\Wkwc_Adyen_Admin_Templates;

/**
 * Integration class
 */
class Wkwc_Adyen_Integration {
	/**
	 * The single instance of the class.
	 *
	 * @var string $instance Wkwc_Adyen_Integration Instance.
	 * @since 2.1.1
	 */
	protected static $instance = null;

	/**
	 * $adyen_helper
	 *
	 * @var Wkwc_Adyen_Helper
	 */
	protected $adyen_helper;

	/**
	 * $adyen_config
	 *
	 * @var Wkwc_Adyen_Config
	 */
	protected $adyen_config;

	/**
	 * $checkout_action
	 *
	 * @var Wkwc_Adyen_Checkout_Action
	 */
	protected $checkout_action;

	/**
	 * Template handler
	 *
	 * @var Wkwc_Adyen_Admin_Templates
	 */
	protected $template_handler;

	/**
	 * Wkwc_Adyen_Integration
	 *
	 * @return Wkwc_Adyen_Integration
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Wkwc_Adyen_Integration constructor.
	 */
	public function __construct() {

		if ( ! $this->is_woocommerce_active() ) {
			return;
		}

		$this->checkout_action  = new Common\Wkwc_Adyen_Checkout_Action();
		$this->adyen_helper     = new Wkwc_Adyen_Helper();
		$this->adyen_config     = $this->adyen_helper->adyen_config;
		$this->template_handler = new Wkwc_Adyen_Admin_Templates();

		add_action( 'admin_init', array( $this, 'wkwc_adyen_register_settings' ) );

		add_action( 'admin_menu', array( $this, 'wkwc_adn_admin_menu' ), 11 );

		add_filter( 'wk_modules_admin_page_slugs', array( $this, 'wkwc_adn_add_pro_menu_pages' ) );

		add_action( 'wkwc-adyen_content', array( $this, 'wkwc_adn_config_content' ) );

		add_filter( 'woocommerce_payment_gateways', array( $this, 'wkwc_adyen_add_adyen_to_woocommerce' ) );

		add_action( 'before_woocommerce_init', array( $this, 'wkwc_adn_declare_cart_checkout_block_compatibility_status' ) );

		add_action( 'woocommerce_admin_order_data_after_order_details', array( $this, 'wkwc_adyen_capture_payment_button' ) );

		add_action( 'init', array( $this, 'wkwc_adyen_get_payment_notification' ) );

		add_action( 'wp_enqueue_scripts', array( $this, 'wkwc_adyen_scripts_and_styles' ) );

		add_action( 'admin_enqueue_scripts', array( $this, 'wkwc_adyen_admin_scripts_and_styles' ) );

		add_filter( 'woocommerce_screen_ids', array( $this, 'wkwc_adyen_set_screens' ) );

		add_action( 'woocommerce_order_edit_status', array( $this, 'wkwc_adyen_refund_through_adyen' ), 99, 2 );

		add_action( 'woocommerce_api_wkwc_adyen', array( $this, 'wkwc_adyen_receive_adyen_notifications' ) );

		add_action( 'wp_ajax_wkwc_capture_payment', array( $this, 'wkwc_capture_payment' ) );

		add_action( 'wp_ajax_wkwc_adyen_get_auth_connection_status', array( $this, 'wkwc_adyen_get_auth_connection_status' ) );
	}

	/**
	 * Enqueue Admin Style And Script.
	 *
	 * @hooked 'admin_enqueue_scripts' action Hook.
	 *
	 * @return void
	 */
	public function wkwc_adyen_admin_scripts_and_styles() {
		wp_enqueue_style( 'wkwc-adyen-admin', WKWC_ADN_PLUGIN_URL . 'assets/admin/css/admin.css', WKWC_ADN_SCRIPT_VERSION, true );
		wp_enqueue_script( 'adyen-admin', WKWC_ADN_PLUGIN_URL . 'assets/admin/js/admin-adyen.js', array(), WKWC_ADN_SCRIPT_VERSION, true );

		$ajax_data = array(
			'ajax_url'                => admin_url( 'admin-ajax.php' ),
			'action'                  => 'wkwc_capture_payment',
			'capture_nonce'           => wp_create_nonce( 'wkwc_capture_payment_info' ),
			'auth_verification_nonce' => wp_create_nonce( 'wkwc_auth_verification_nonce' ),
			'translation'             => array(
				'processing' => __( 'processing...', 'wkwc-adyen' ),
				'saving'     => __( 'saving...', 'wkwc-adyen' ),
			),
		);

		$wkwc_adyen_util = $this->wkwc_adyen_localize_utils();

		wp_localize_script( 'adyen-admin', 'wkwc_adyen_util', $wkwc_adyen_util );
		wp_localize_script( 'adyen-admin', 'adyen_capture_data', $ajax_data );
	}

	/**
	 * Enqueue Style And Script.
	 *
	 * @hooked 'wp_enqueue_scripts' action Hook.
	 *
	 * @return void
	 */
	public function wkwc_adyen_scripts_and_styles() {
		if ( ! is_checkout() ) {
			return;
		}

		$env = $this->adyen_helper->adyen_config->wkwc_adyen_get_environment();

		wp_enqueue_script( 'adyen-sdk', WKWC_ADN_PLUGIN_URL . 'assets/front/js/adyen-' . $env . '.min.js', array(), '5.10.0', true );
		wp_enqueue_style( 'adyen', WKWC_ADN_PLUGIN_URL . 'assets/front/css/adyen.min.css' );
		$this->wkwc_adn_front_scripts_and_styles();
	}

	/**
	 * Add Quote page in WooCommerce Screens.
	 *
	 * @param array $screens screen.
	 * @since 2.0.0
	 * @return array || Update Screen Lists
	 */
	public function wkwc_adyen_set_screens( $screens ) {
		$screen = get_current_screen();
		// Check if this is the target page where you want to add screen options.
		if ( 'webkul-wc-addons_page_wkwc-adyen' === $screen->id ) {
			$get_data = wp_unslash( $_REQUEST );//PHPCS:ignore

			if ( isset( $get_data['page'] ) && 'wkwc-adyen' === $get_data['page'] ) {
				$screens[] = 'webkul-wc-addons_page_wkwc-adyen';
			}
		}

		return $screens;
	}

	/**
	 * Register Option Settings
	 *
	 * @return void
	 */
	public function wkwc_adyen_register_settings() {
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_enabled' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_test_mode_enabled' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_immediate_capturing_enabled' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_refund_enabled' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_test_api_key' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_test_merchant_account' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_test_origin_key' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_live_api_key' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_live_merchant_account' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_live_origin_key' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_live_endpoint_prefix' );
		register_setting( 'wkwc-adyen-settings-group', '_wkwc_adyen_hmac_key' );
	}


	/**
	 * Admin menu callback.
	 *
	 * @hooked at 'admin_menu' action hook.
	 */
	public function wkwc_adn_admin_menu() {

		$menus_list = apply_filters( 'wk_modules_admin_page_slugs', array() );

		// Here is my UNIQUE KEY in $menus_list check.
		if ( ! empty( $menus_list['wkwc_adn'] ) ) {
			wkwc_create_menu( $menus_list['wkwc_adn'], $this );
		}

		do_action( 'wkwc_adn_admin_menu_action' );
	}


	/**
	 * Adding submenu for dynamically created via license verification script.
	 *
	 * @param array $menu_array Menu array.
	 *
	 * @return array
	 */
	public function wkwc_adn_add_pro_menu_pages( $menu_array = array() ) {
		$capability             = apply_filters( 'wkmp_dashboard_menu_capability', 'manage_options' );
		$menu_array['wkwc_adn'] = array(
			array(
				'parent_slug'   => 'wkwc-addons',
				'page_title'    => esc_html__( 'Adyen Payment', 'wkwc-adyen' ),
				'menu_title'    => esc_html__( 'Adyen Payment', 'wkwc-adyen' ),
				'menu_slug'     => 'wkwc-adyen',
				'capability'    => $capability,
				'callback'      => 'wkwc_adn_submenu_callback',
				'screen_option' => false,
			),
		);
		return $menu_array;
	}


	/**
	 * Setting tabs to create.
	 */
	public function wkwc_adn_submenu_callback() {
		$tabs = array(
			'wkwc-adyen' => esc_html__( 'Configuration', 'wkwc-adyen' ),
		);

		if ( class_exists( 'WKWC_Addons' ) ) {
			$addon = \WKWC_Addons::get_instance();
			$title = esc_html__( 'Adyen Payment', 'wkwc-adyen' );
			$icon  = '<img src="' . WKWC_ADN_PLUGIN_URL . 'assets/admin/img/adyen-icon.png" alt="" style="max-width:30px;" />';

			$addon->create_settings_tabs( $tabs, $title, $icon );
		}
	}


	/**
	 * Setting tabs content.
	 */
	public function wkwc_adn_config_content() {
		$this->template_handler->wkwc_adyen_configuration();
	}

	/**
	 * Loads the needed scripts and styles.
	 */
	public function wkwc_adn_front_scripts_and_styles() {

		$admin_data = $this->adyen_helper->wkwc_adyen_get_config();

		$adyen_payment_enabled = ( isset( $admin_data['enabled'] ) && 'yes' === $admin_data['enabled'] ) ? $admin_data['enabled'] : '';

		if ( ! empty( $adyen_payment_enabled ) && 'yes' === $adyen_payment_enabled ) {
			$wkwc_adyen_util = $this->wkwc_adyen_localize_utils();
			if ( is_checkout() ) {
				wp_enqueue_script(
					'wkwc-adyen-popup',
					WKADYEN_PLUGIN_URL . 'assets/front/js/jquery.popupoverlay.js',
					array( 'jquery' ),
					WKADYEN_VERSION,
					true
				);

				wp_enqueue_script(
					'wkwc-adyen-checkout',
					WKADYEN_PLUGIN_URL . 'assets/front/js/wkwc-adyen-checkout.js',
					array( 'jquery', 'adyen-sdk' ),
					'1.5.0',
					true
				);

				wp_localize_script(
					'wkwc-adyen-checkout',
					'wkwc_adyen_util',
					$wkwc_adyen_util
				);

				wp_enqueue_style( 'wkwc-adyen-checkout', WKWC_ADN_PLUGIN_URL . 'assets/front/css/checkout.css', null, '1.6.0', 'all' );

			}
		}
	}

	/**
	 * Localize utility
	 *
	 * @return mixed
	 */
	public function wkwc_adyen_localize_utils() {
		$admin_data    = $this->adyen_helper->wkwc_adyen_get_config();
		$origin_key    = '';
		$merchant_code = '';
		if ( isset( $admin_data['test_mode'] ) && 'yes' === $admin_data['test_mode'] ) {
			$origin_key = $admin_data['test_origin_key'];
		} else {
			$origin_key = $admin_data['live_origin_key'];
		}

		if ( isset( $admin_data['test_mode'] ) && 'yes' === $admin_data['test_mode'] ) {
			$merchant_code = $admin_data['test_merchant'];
		} else {
			$merchant_code = $admin_data['live_merchant_account'];
		}

		$environment = ( isset( $admin_data['test_mode'] ) && 'yes' === $admin_data['test_mode'] ) ? 'test' : 'live';

		$credit_card_gateway = new Payment_Methods\Wkwc_Adyen_Credit_Card();
		$google_gateway      = new Payment_Methods\Wkwc_Adyen_Googlepay();
		$apple_gateway       = new Payment_Methods\Wkwc_Adyen_Applepay();

		$payment_methods = $this->checkout_action->list_payment_methods();

		$payment_methods['storedPaymentMethods'] = $this->checkout_action->get_ec_stored_cards();

		$card_holder_is_required = $credit_card_gateway->get_option( 'require_card_holder_name' );
		$store_card              = $credit_card_gateway::has_subscription() ? false : true;
		$store_card              = is_user_logged_in() ? $store_card : false;
		$non_apple_device_desc   = $apple_gateway->get_option( 'no_apple_device_description' );
		// Localize wkwc_adyen_util data
		$wkwc_adyen_util = array(
			'ajax'               => array(
				'url'   => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wkwc_adyen_nonce' ),
			),
			'prefix'             => 'wkwc_adyen',
			'translation'        => array(
				'processing'      => array( 'processing...', 'Processing...' ),
				'saving'          => 'saving...',
				'remove_card'     => 'Are you sure you want to remove this card?',
				'use_a_new_card'  => __( 'Use a new card', 'wkwc-adyen' ),
				'no_apple_device' => $non_apple_device_desc,
			),
			'debug'              => '',
			'checkout_url'       => get_permalink( wc_get_page_id( 'checkout' ) ),
			'locale'             => get_locale(),
			'api'                => array(
				'origin_key'               => $origin_key,
				'environment'              => $environment,
				'adyen_merchant'           => $merchant_code,
				'card_types'               => $this->checkout_action->get_card_types(),
				'response_payment_methods' => $payment_methods,
				'store_card'               => $store_card,
				'has_holder_name'          => true,
				'holder_name_required'     => ( 'yes' === $card_holder_is_required ) ? true : false,
			),
			'site_name'          => get_bloginfo( 'name' ),
			'currency'           => get_woocommerce_currency(),
			'cart'               => array(
				'country' => ( null !== WC()->customer ) ? WC()->customer->get_billing_country() : '',
				'total'   => isset( WC()->cart->total ) ? WC()->cart->total : 0,
			),
			'google_method_type' => $google_gateway->payment_method_type(),
		);

		return $wkwc_adyen_util;
	}

	/**
	 * Activate New Payment Gateway.
	 *
	 * @hooked 'woocommerce_order_edit_status' action Hook.
	 * @param array $gateways existing gateway.
	 *
	 * @return array
	 */
	public function wkwc_adyen_add_adyen_to_woocommerce( $gateways ) {
		$gateways[] = Payment_Methods\Wkwc_Adyen_Credit_Card::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Googlepay::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Klarna::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Klarna_PayNow::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Klarna_Account::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Klarna_Ideal::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Amazonpay::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Paypal::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Twint::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Trustly::class;
		$gateways[] = Payment_Methods\Wkwc_Adyen_Applepay::class;

		return $gateways;
	}

	/**
	 * Declare plugin is incompatible with WC Cart and Checkout blocks.
	 *
	 * @return void
	 */
	public function wkwc_adn_declare_cart_checkout_block_compatibility_status() {
		if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', WKADYEN_FILE, false );
		}

		if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', WKADYEN_FILE, true );
		}
	}

	/**
	 * Renders capture payment button.
	 *
	 * @since 1.1.0 - add capture button for manual payment methods
	 * @since 1.0.3
	 * @param WC_Order $order order data.
	 * @return string
	 */
	public function wkwc_adyen_capture_payment_button( $order ) {
		$admin_data = $this->adyen_helper->wkwc_adyen_get_config();
		$capture    = isset( $admin_data['immediate_capturing'] ) && ! empty( $admin_data['immediate_capturing'] ) ? $admin_data['immediate_capturing'] : 'no';

		$payment_mode = $order->get_meta( 'wkwc_adyen_mode', true );
		$is_captured  = $order->get_meta( '_wkwc_adyen_payment_captured', true );

		if ( 'yes' === $is_captured || 'yes' === $capture || 'authorize_payment' !== $payment_mode ) {
			return;
		}
		?>
		<div class="form-field form-field-wide">
			<h3><?php _e( 'Capture Payment', 'wkwc-adyen' ); ?></h3>
			<p><?php _e( 'To capture the payment', 'wkwc-adyen' ); ?></p>
			<p>
				<button type="button" class="button" data-capture-order-payment="<?php echo esc_attr( $order->get_id() ); ?>"><?php _e( 'Capture', 'wkwc-adyen' ); ?></button>
			</p>
		</div>
		<?php
	}

	/**
	 * Get auth status.
	 *
	 * @since 1.0.3
	 * @return string
	 */
	public function wkwc_adyen_get_auth_connection_status() {
		// Check to make sure the request is from same server.
		if ( ! check_ajax_referer( 'wkwc_auth_verification_nonce', 'security', false ) ) {
			return;
		}

		$url         = $this->checkout_action->wkwc_adyen_checkout_base_url();
		$api_handler = new Common\Wkwc_Adyen_Api_Handler( $url );

		$payload = array(
			'merchantAccount'  => $this->adyen_config->wkwc_adyen_get_merchantcode(),
			'shopperReference' => $this->adyen_helper::get_shopper_reference(),
			'channel'          => 'Web',
		);

		$response      = $api_handler->wkwc_adyen_remote_post( 'paymentMethods', $payload );
		$response_body = $response->body;
		if ( $response->status == 200 ) {
			set_transient( 'wkwc_adyen_merchant_account_is_validated', $this->adyen_config->wkwc_adyen_get_merchantcode(), DAY_IN_SECONDS );
			// Successfully connected
				wp_send_json_success(
					array(
						'message' => 'Connection successful. Credentials are valid.',
						'data'    => $response_body,
					)
				);
		} else {
			set_transient( 'wkwc_adyen_merchant_account_is_validated', null, DAY_IN_SECONDS );
			// Failed to connect; return the error message
				wp_send_json_error(
					array(
						'message' => 'Connection failed. Please check your credentials.',
						'error'   => $response_body,
					)
				);
		}
	}

	/**
	 * Captures payments.
	 *
	 * @since 1.0.3
	 * @return string
	 */
	public function wkwc_capture_payment() {
		// Check to make sure the request is from same server.
		if ( ! check_ajax_referer( 'wkwc_capture_payment_info', 'security', false ) ) {
			return;
		}
		$response = array();
		$order_id = isset( $_POST['order_id'] ) ? wc_clean( $_POST['order_id'] ) : '';
		$order    = wc_get_order( $order_id );

		$reference = $order->get_meta( '_' . WKWC_ADN_PREFIX . '_payment_pspReference' );

		$amount = $order->get_total();

		$response = $this->checkout_action->capture_payment( $reference, $amount );

		if ( $response->status == 201 ) {

			$order->payment_complete( $reference );

			/* translators: %s: is Transaction reference */
			$order->add_order_note( sprintf( __( 'Payment was complete via Adyen (PSP Reference: %s)', 'wkwc-adyen' ), $this->adyen_helper->wkwc_adyen_get_adyen_transaction_url( $reference ) ) );

			$order->update_meta_data( '_wkwc_adyen_payment_captured', 'yes' );

			$order->save();

			$response = array(
				'result'  => 'success',
				'message' => 'payment captured successfully',
			);
		} else {
			$response = array(
				'result'  => 'error',
				'message' => 'something was wrong',
			);
			add_action( 'admin_notices', array( $this, 'wkwc_adyen_order_payment_capture_notice' ) );
		}

		$response = wp_json_encode( $response );

		return wp_send_json( $response );
	}

	/**
	 * Admin notice function for Order Payment Capture Failed
	 */
	public function wkwc_adyen_order_payment_capture_notice() {
		?>
		<div class="error">
			<p>
				<?php
				printf( /* Translators: %s adyen php library links */
					esc_html__( 'Adyen payment gateway is enabled but not effective. It requires Adyen library in order to work. %1$sHow to install%2$s', 'wkwc-adyen' ),
					'<a href="' . esc_url( 'https://webkul.com/blog/woocommerce-adyen-payment-gateway/' ) . '" target="_blank">',
					'</a>'
				);
				?>
			</p>
		</div>
		<?php
	}

	/**
	 * Notification hook. Get the Payment by link Data
	 *
	 * @since 1.1.0
	 * @version 1.1.0
	 *
	 * @return void
	 */
	public function wkwc_adyen_get_payment_notification() {
		if ( isset( WC()->session ) && ! empty( WC()->session->get( 'adyen_linked_id' ) ) ) {
			$link_id = WC()->session->get( 'adyen_linked_id' );

			$payment_info = $this->get_payment_status_by_linked_id( $link_id );
			$payment_info = $payment_info->data;

			if ( isset( $payment_info['status'] ) && 'completed' === $payment_info['status'] ) {
				$order_id = $payment_info['reference'];
				$order    = wc_get_order( $order_id );
				$order->payment_complete( $payment_info['id'] );

				$order->add_order_note( esc_html__( 'Adyen transaction reference: ', 'wkwc-adyen' ) . $payment_info['id'] );
				$order->add_order_note( esc_html__( 'Your payment was successful on Adyen, we are now processing your order.', 'wkwc-adyen' ), 1 );

				$order->update_meta_data( 'wkadyen_transaction_reference', $payment_info['id'] );
				$order->save();

				WC()->session->__unset( 'adyen_linked_id' );
			}
		}
	}

	/**
	 * Get adyen payment status by payment linked if
	 *
	 * @param string $link_id payment link id.
	 *
	 * @return object $response
	 */
	public function get_payment_status_by_linked_id( $link_id ) {

		$response = $this->checkout_action->payment_link_details( $link_id );

		$body_response = $this->adyen_helper::wkwc_adyen_obj_to_arr( $response->body );

		return rest_ensure_response( $body_response );
	}

	/**
	 * Refund Through Adyen.
	 *
	 * @hooked 'woocommerce_order_edit_status' action Hook.
	 * @param int    $order_id order id.
	 * @param string $new_status updated Status.
	 *
	 * @return void
	 */
	public function wkwc_adyen_refund_through_adyen( $order_id, $new_status ) {
		if ( ! in_array( $new_status, array( 'cancelled', 'refunded' ), true ) ) {
			return;
		}

		$order              = new WC_Order( $order_id );
		$gateway_controller = WC_Payment_Gateways::instance();
		$all_gateways       = $gateway_controller->payment_gateways();
		$payment_method     = $order->get_payment_method();
		$gateway            = isset( $all_gateways[ $payment_method ] ) ? $all_gateways[ $payment_method ] : false;

		if ( $gateway instanceof Wkwc_Adyen_Payment_Gateway && $gateway->can_refund_order( $order ) ) {
			if ( $gateway->adyen_config->wkwc_adyen_is_refund_in_adyen() ) {
				$adyen = new Wkwc_Adyen_Helper( $gateway->adyen_config );
				$adyen->wkwc_adyen_refund( $order );
			}
		}
	}

	/**
	 * Receive Notification
	 *
	 * @hooked 'woocommerce_api_wc_adyen' action Hook.
	 *
	 * @return void
	 */
	public function wkwc_adyen_receive_adyen_notifications() {
		$data = json_decode( file_get_contents( 'php://input' ), true );

		if ( empty( $data ) ) {
			// required by Adyen in order to acknowledge the notification.
			echo '[accepted]';
			exit;
		}

		wkwc_adn_log( '3DS result data: ' . print_r( $data, true ) );

		$notification_request = wp_unslash( $data );

		if ( isset( $notification_request['notificationItems'] ) && ! empty( $notification_request['notificationItems'] ) ) {
			foreach ( $notification_request['notificationItems'] as $notification_item ) {
				wkwc_adn_log( 'Notification data: ' . print_r( $notification_item, true ) );

				$notification_item = new Wkwc_Adyen_Notification_Request( $notification_item['NotificationRequestItem'] );
				$event_handler     = Wkwc_Handlers_Factory::make( $notification_item->event_code );

				if ( ! $event_handler instanceof Wkwc_Abstract_Handler ) {
					continue;
				}

				wkwc_adn_log( 'Event code: ' . $notification_item->event_code . ' Handler: ' . print_r( $event_handler, true ) );

				$hmackey = $this->adyen_helper->adyen_config->wkwc_adyen_get_hmackey();

				if ( $event_handler->verify( $notification_item, $hmackey ) ) {
					wkwc_adn_log( 'Verified hmac key is: ' . $hmackey );
					$event_handler->store( $notification_item );
					$event_handler->handle( $notification_item );
				}
			}
		}

	}

	/**
	 * Woocommerce Activated Or Not
	 *
	 * @return array
	 */
	private function is_woocommerce_active() {
		$active_plugins = (array) get_option( 'active_plugins', array() );

		return in_array( 'woocommerce/woocommerce.php', $active_plugins, true ) || array_key_exists( 'woocommerce/woocommerce.php', $active_plugins );
	}
}
