<?php
/**
 * Amazon Pay
 */

namespace WkwcAdyen\Includes\Payment_Methods;

// prevent direct access data leaks
use Automattic\WooCommerce\StoreApi\Utilities\NoticeHandler;

defined( 'ABSPATH' ) || exit;

use Amazon\Pay\API;
use WkwcAdyen\Helper\Common\Wkwc_Adyen_Service_Util;

use WkwcAdyen\Helper\Common\Wkwc_Adyen_Checkout_Action;

class Wkwc_Adyen_Amazonpay extends Wkwc_Adyen_Abstract_Gateway {

	/**
	 * Checkout action instance
	 *
	 * @var Wkwc_Adyen_Checkout_Action
	 */
	public $checkout_action;

	/**
	 * Helper to store the current refund being handled
	 *
	 * @var array
	 */
	protected static $amazonpay_sdk_config;

	/**
	 * Helper to store the current refund being handled
	 *
	 * @var \Amazon\Pay\API\Client
	 */
	protected static $amazonpay_client;

	/**
	 * Merchant identifier of the Solution Provider (SP).
	 *
	 * @see https://developer.amazon.com/docs/amazon-pay-api-v2/checkout-session.html#ERL9CA7OsPD
	 */
	const AMAZON_PAY_FOR_WOOCOMMERCE_SP_ID = 'A1BVJDFFHQ7US4';

	/**
	 * Constructor of this class.
	 *
	 * @param bool $init_hooks
	 * @since 1.0.4
	 * @since 1.1.0 - add support for subscriptions
	 */
	public function __construct( $init_hooks = true ) {

		parent::__construct( $init_hooks );
		$this->checkout_action = new Wkwc_Adyen_Checkout_Action();
		$this->has_fields      = true;
	}


	/**
	 * List of countries where is available.
	 *
	 * @since 1.1.0
	 * @return array
	 */
	public function available_countries() {

		return array(
			'AU' => array(
				'currencies' => array( 'AUD' ),
				'recurring'  => false,
			),
			'AT' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'FI' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'BE' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'CY' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'DE' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'DK' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'FR' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'HU' => array(
				'currencies' => array( 'HUF' ),
				'recurring'  => false,
			),
			'IE' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'IT' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'LU' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'PT' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'NO' => array(
				'currencies' => array( 'NOK' ),
				'recurring'  => false,
			),
			'ES' => array(
				'currencies' => array( 'EUR' ),
				'recurring'  => false,
			),
			'GB' => array(
				'currencies' => array( 'GBP' ),
				'recurring'  => false,
			),
			'UK' => array(
				'currencies' => array( 'GBP' ),
				'recurring'  => true,
			),
			'US' => array(
				'currencies' => array( 'USD' ),
				'recurring'  => true,
			),
		);
	}

	/**
	 * Gets default payment method title.
	 *
	 * @since 1.0.4
	 * @return string
	 */
	public function get_default_title() {
		return __( 'Adyen - Amazon Pay', 'wkwc-adyen' );
	}



	/**
	 * Gets default payment method description.
	 *
	 * @since 1.1.0 - display supported countries
	 * @since 1.0.4
	 * @return string
	 */
	public function get_default_description() {
		return $this->show_supported_country();
	}



	/**
	 * Gets default description set in settings.
	 *
	 * @since 1.0.4
	 * @return string
	 */
	public function get_settings_description() {
		$this->description = ( $this->settings['description'] ) ? $this->settings['description'] : __( 'Pay with amazon pay', 'wkwc-adyen' );
		return $this->description;
	}

	/**
	 * Type of the payment method (e.g ideal, scheme. bcmc).
	 *
	 * @since 1.0.0
	 * @return string
	 */
	public function payment_method_type() {
		return 'amazonpay';
	}


	/**
	 * Returns the payment method to be used for recurring payments
	 *
	 * @since 1.1.0 - add recurring method type
	 * @since 1.0.4
	 * @return string
	 */
	public function recurring_payment_method() {
		return $this->payment_method_type();
	}



	/**
	 * Adds extra fields.
	 *
	 * @since 1.0.4
	 * @return void
	 */
	public function payment_fields() {

		parent::payment_fields();

		echo $this->generate_extra_fields_html();
	}



	/**
	 * Generates extra fields HTML.
	 *
	 * @since 1.0.4
	 * @return string
	 */
	public function generate_extra_fields_html() {

		$description = WC()->session->get( $this->id . '_description' );

		?>
		<div id="<?php echo esc_attr( WKWC_ADN_PREFIX . '-amazonpay-container' ); ?>">
			<div id="<?php echo esc_attr( $this->id . '_button' ); ?>"></div>
			<div class="amazonpay-description" style=""><?php echo esc_html( $description ); ?></div>
			<input type="hidden" id="<?php echo esc_attr( $this->id . '_merchant_id' ); ?>" name="<?php echo esc_attr( $this->id . '_merchant_id' ); ?>" value="<?php echo esc_attr( $this->get_option( 'merchant_id' ) ); ?>">
			<input type="hidden" id="<?php echo esc_attr( $this->id . '_token' ); ?>" name="<?php echo esc_attr( $this->id . '_token' ); ?>" value=''>
			<input type="hidden" id="<?php echo esc_attr( $this->id . '_testmode' ); ?>" value="<?php echo esc_attr( $this->get_option( 'testmode', 'yes' ) ); ?>">
		</div>
		<?php
	}



	/**
	 * Validates extra added fields.
	 *
	 * @since 1.0.4
	 * @return bool
	 */
	public function validate_fields() {

		$is_valid    = parent::validate_fields();
		$merchant_id = $_POST[ $this->id . '_merchant_id' ];

		if ( empty( $merchant_id ) ) {
			wc_add_notice( __( 'Sorry it looks like merchant id is not set, please refresh the page and try again!', 'wkwc-adyen' ), 'error' );
			$is_valid = false;
		}

		return $is_valid;
	}


	/**
	 * Builds the required payment payload
	 *
	 * @since 1.1.0 - use parent function to get common data
	 * @since 1.0.4
	 * @param \WC_Order $order
	 * @param string    $reference
	 * @return array
	 */
	public function build_payment_payload( \WC_Order $order, $reference ) {

		$payload = parent::build_payment_payload( $order, $reference );

		$checkout_session = $this->create_amazonpay_checkout_session( $order );

		$checkout_session_id = $checkout_session['checkoutSessionId'];

		$payload['paymentMethod']['checkoutSessionId'] = $checkout_session_id;

		return $payload;
	}

	/**
	 * Location type detection.
	 *
	 * @param  object $location Location to check.
	 * @return boolean
	 */
	private static function location_is_continent( $location ) {
		return 'continent' === $location->type;
	}

	/**
	 * Location type detection.
	 *
	 * @param  object $location Location to check.
	 * @return boolean
	 */
	private static function location_is_country( $location ) {
		return 'country' === $location->type;
	}

	/**
	 * Location type detection.
	 *
	 * @param  object $location Location to check.
	 * @return boolean
	 */
	private static function location_is_state( $location ) {
		return 'state' === $location->type;
	}

	/**
	 * Location type detection.
	 *
	 * @param  object $location Location to check.
	 * @return boolean
	 */
	private static function location_is_postcode( $location ) {
		return 'postcode' === $location->type;
	}

	/**
	 * Get Merchant Metadata object
	 *
	 * @param  int $order_id Order ID.
	 * @return array
	 */
	public static function get_merchant_metadata( $order_id ) {
		/* translators: Plugin version */
		$version_note = sprintf( 'Created by WC_Gateway_Amazon_Pay/%1$s (Platform=WooCommerce/%2$s)', WKADYEN_VERSION, WC()->version );

		$merchant_metadata = array(
			'merchantReferenceId' => apply_filters( 'woocommerce_wkwc_adyen_amazonpay_merchant_metadata_reference_id', $order_id ),
			'customInformation'   => $version_note,
		);

		$site_name = get_bloginfo( 'name' );
		if ( 50 >= strlen( $site_name ) ) {
			$merchant_metadata['merchantStoreName'] = $site_name;
		}

		return $merchant_metadata;
	}

	/**
	 * Return shipping restrictions for checkout sessions
	 *
	 * @return bool|array
	 */
	protected static function get_shipping_restrictions() {
		$data_store         = \WC_Data_Store::load( 'shipping-zone' );
		$raw_zones          = $data_store->get_zones();
		$zones              = array();
		$shipping_countries = WC()->countries->get_shipping_countries();

		$all_continents = WC()->countries->get_continents();
		$all_countries  = WC()->countries->get_countries();
		$all_states     = WC()->countries->get_states();

		$row_zone = new \WC_Shipping_Zone( 0 );
		$methods  = $row_zone->get_shipping_methods( true, 'json' );
		if ( ! empty( $methods ) ) {
			// Rest of the World has shipping methods, so we can assume we can ship to all shipping countries
			// Skip the whole thing.
			if ( count( $shipping_countries ) !== count( $all_countries ) ) {
				foreach ( $shipping_countries as $country => $name ) {
					$zones[ $country ] = new stdClass(); // If we use an empty array it'll be treated as an array in JSON.
				}
				return $zones;
			} else {
				return false; // No restrictions.
			}
		}

		foreach ( $raw_zones as $raw_zone ) {
			$zone    = new \WC_Shipping_Zone( $raw_zone );
			$methods = $zone->get_shipping_methods( true, 'json' );
			if ( empty( $methods ) ) {
				continue; // If no shipping methods, we assume no support on this region.
			}

			$locations  = $zone->get_zone_locations( 'json' );
			$continents = array_filter( $locations, array( __CLASS__, 'location_is_continent' ) );
			$countries  = array_filter( $locations, array( __CLASS__, 'location_is_country' ) );
			$states     = array_filter( $locations, array( __CLASS__, 'location_is_state' ) );
			$postcodes  = array_filter( $locations, array( __CLASS__, 'location_is_postcode' ) ); // HARD TODO: Postcode wildcards can't be implemented afaik.

			foreach ( $continents as $location ) {
				foreach ( $all_continents[ $location->code ]['countries'] as $country ) {
					if ( ! isset( $zones[ $country ] ) ) {
						$zones[ $country ] = new \stdClass(); // If we use an empty array it'll be treated as an array in JSON.
					}
				}
			}

			foreach ( $countries as $location ) {
				$country = $location->code;
				// We're forcing it to be an empty, since it will override if the full country is allowed anywhere.
				$zones[ $country ] = new \stdClass(); // If we use an empty array it'll be treated as an array in JSON.
			}

			foreach ( $states as $location ) {
				$location_codes = explode( ':', $location->code );
				$country        = strtoupper( $location_codes[0] );
				$state          = $location_codes[1];
				if ( ! isset( $zones[ $country ] ) ) {
					$zones[ $country ]                  = new \stdClass(); // If we use an empty array it'll be treated as an array in JSON.
					$zones[ $country ]->statesOrRegions = array();
				} elseif ( ! isset( $zones[ $country ]->statesOrRegions ) ) {
						// Do not override anything if the country is allowed fully.
						continue;
				}

				$zones[ $country ]->statesOrRegions[] = $state;
				if ( 'US' !== $country ) {

					$zones[ $country ]->statesOrRegions[] = $all_states[ $country ][ $state ];
					$variation_state                      = self::remove_signs( $all_states[ $country ][ $state ] );
					if ( $variation_state !== $all_states[ $country ][ $state ] ) {
						$zones[ $country ]->statesOrRegions[] = $variation_state;
					}
				}
			}
		}

		$zones = array_intersect_key( $zones, $shipping_countries );

		return $zones;
	}


	/**
	 * Create classic checkout session parameters for button.
	 *
	 * @param object $order Order object.
	 * @param string $redirect_url Redirect URL on success.
	 * @return array
	 */
	public function create_checkout_session_classic_params( $order, $redirect_url = null ) {

		$settings = self::get_settings();
		if ( is_null( $redirect_url ) ) {
			if ( function_exists( 'is_checkout_pay_page' ) && is_checkout_pay_page() ) {
				$parts        = wp_parse_url( home_url() );
				$path         = ! empty( $parts['path'] ) ? $parts['path'] : '';
				$redirect_url = "{$parts['scheme']}://{$parts['host']}{$path}" . add_query_arg( null, null );
			} else {
				$redirect_url = get_permalink( wc_get_page_id( 'checkout' ) );
			}
		}
		$redirect_url = add_query_arg( 'amazon_payments_advanced', 'true', $redirect_url );
		$payload      = array(
			'storeId'            => $settings['store_id'],
			'platformId'         => self::AMAZON_PAY_FOR_WOOCOMMERCE_SP_ID,
			'webCheckoutDetails' => array(
				'checkoutReviewReturnUrl' => $this->get_return_url( $order ),
				'checkoutResultReturnUrl' => add_query_arg( 'amazon_return_classic', '1', $redirect_url ),
			),
		);

		$restrictions = false;

		if ( $restrictions ) {
			$payload['deliverySpecifications'] = array(
				'addressRestrictions' => array(
					'type'         => 'Allowed',
					'restrictions' => $restrictions,
				),
			);
		}

		$payload = apply_filters( 'woocommerce_amazon_pa_create_checkout_session_classic_params', $payload, $redirect_url );

		return $payload;
	}

	/**
	 * Get classic checkout session parameters for session.
	 *
	 * @param object $order
	 * @return array
	 */
	public function get_wkwc_adyen_amazonpay_classic_handler( \WC_Order $order ) {

		$order_id = $order->get_id();

		$payload = $this->create_checkout_session_classic_params( $order, $order->get_checkout_payment_url() );

		$settings = self::get_settings();

		$order_total = $this->adyen_helper->wkwc_adyen_format_amount( $order->get_order_total() );

		$payment_intent = 'AuthorizeWithCapture';

		switch ( $settings['payment_capture'] ) {
			case 'authorize':
				$payment_intent = 'Authorize';
				break;
			case 'manual':
				$payment_intent = 'Confirm';
				break;
		}

		$can_do_async = false;

		$charge_amount = array(
			'amount'       => number_format( $order_total / 100, 2, '.', '' ), // Amazon expects major units
			'currencyCode' => get_woocommerce_currency(),
		);

		$payload['paymentDetails'] = array_merge(
			isset( $payload['paymentDetails'] ) && is_array( $payload['paymentDetails'] ) ? $payload['paymentDetails'] : array(),
			array(
				'paymentIntent'                 => $payment_intent,
				'canHandlePendingAuthorization' => $can_do_async,
				'chargeAmount'                  => $charge_amount,
			)
		);

		$payload['merchantMetadata'] = self::get_merchant_metadata( $order_id );

		$payload = apply_filters( 'woocommerce_wkwc_adyen_amazonpay_update_checkout_session_payload', $payload, $order );

		return $payload;

		return self::get_create_checkout_classic_session_config( $payload );
	}


	/**
	 * Set up API V2 SDK.
	 *
	 * @since 2.0.0
	 * @param  bool $fresh Force refresh, or get from cache.
	 *
	 * @return array Returns SDK configuration
	 */
	protected static function get_amazonpay_sdk_config( $fresh = false ) {
		if ( $fresh || empty( self::$amazonpay_sdk_config ) ) {

			$region = 'eu'; // TODO: Maybe normalize v1 and v2 different region management.
			if ( 'gb' === $region ) {
				$region = 'eu';
			}

			self::$amazonpay_sdk_config = array(
				'public_key_id' => 'AGF664XON7SE3N5IX23JJU7I',
				'private_key'   => file_get_contents( WKWC_ADN_PLUGIN_FILE . 'helper/adyen/AmazonPay_AGF664XON7SE3N5IX23JJU7I.pem' ),
				'sandbox'       => true,
				'region'        => $region,
			);

		}
		return self::$amazonpay_sdk_config;
	}


	/**
	 * Get Amazon Pay SDK Client
	 *
	 * @since 2.0.0
	 *
	 * @return Amazon\Pay\API\Client Instance
	 */
	protected static function get_client() {
		if ( isset( self::$amazonpay_client ) ) {
			return self::$amazonpay_client;
		}

		self::$amazonpay_client = new API\Client( self::get_amazonpay_sdk_config( true ) );

		return self::$amazonpay_client;
	}


	/**
	 * Get classic create checkout session config to send to Amazon.
	 *
	 * @param  array $payload The payload that will be used to create a checkout session.
	 * @return array
	 */
	public static function get_create_checkout_classic_session_config( $payload ) {
		ksort( $payload );
		$signature = self::get_client()->generateButtonSignature( wp_json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) );
		return array(
			'publicKeyId' => 'AGF664XON7SE3N5IX23JJU7I',
			'payloadJSON' => $payload,
			'signature'   => $signature,
		);
	}

	/**
	 * Create Amazon Checkout Session
	 *
	 * @param object $order order info
	 *
	 * @return mixed
	 */
	public function create_amazonpay_checkout_session( $order ) {

		$order_id = $order->get_id();

		$amazonpay_config = array(
			'public_key_id' => 'AGF664XON7SE3N5IX23JJU7I',
			'private_key'   => get_option( 'woocommerce_wkwc_adyen_amazon_payments_advanced_private_key', true ),
			'region'        => 'EU',
			'sandbox'       => true,
			'algorithm'     => 'AMZN-PAY-RSASSA-PSS-V2',
		);

		$payload = $this->get_wkwc_adyen_amazonpay_classic_handler( $order );

		$headers = array( 'x-amz-pay-Idempotency-Key' => uniqid() );

		try {
			$client = new API\Client( $amazonpay_config );

			$result = $client->createCheckoutSession( $payload, $headers );

			if ( $result['status'] === 201 ) {
				// created
				$response = json_decode( $result['response'], true );

				return $response;
			} else {
				// check the error
				echo 'status=' . $result['status'] . '; response=' . $result['response'] . "\n";
			}
		} catch ( \Exception $e ) {
			// handle the exception
			echo $e . "\n";
		}
	}


	/**
	 * Processes the payment.
	 *
	 * @since 1.1.0 - add support for subscriptions
	 * @since 1.0.4
	 * @param int $order_id
	 * @return array
	 */
	public function process_payment( $order_id ) {

		parent::process_payment( $order_id );

		$order = wc_get_order( $order_id );

		$reference = $order_id;

		$payload = $this->build_payment_payload( $order, $reference );

		$response = $this->checkout_action->send_payment( $payload );

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

			return $this->process_payment_result( $response, $order );

		} else {

			wc_add_notice( $response->body['message'], 'error' );

			NoticeHandler::convert_notices_to_exceptions( 'woocommerce_rest_payment_error' );

		}

		return array( 'result' => 'failure' );
	}


	/**
	 * Processes the payment result.
	 *
	 * @since 1.3.0
	 * @param object    $response
	 * @param \WC_Order $order
	 * @return array
	 */
	protected function process_payment_result( $response, $order ) {
		$body_response = $this->adyen_helper::wkwc_adyen_obj_to_arr( $response->body );

		$result_code = $body_response['resultCode'];
		$reference   = $body_response['pspReference'];
		$action      = $body_response['action'];

		$result = array(
			'result'   => 'success',
			'redirect' => Wkwc_Adyen_Service_Util::get_return_page_url( $order, $result_code ),
		);

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

		if ( $order_psp_reference !== $reference ) {

			$order->update_meta_data( '_' . WKWC_ADN_PREFIX . '_payment_pspReference', $reference );

		}

		$order->update_meta_data( '_' . WKWC_ADN_PREFIX . '_payment_resultCode', $result_code );
		$order->update_meta_data( '_' . WKWC_ADN_PREFIX . '_payment_action', $action );
		$order->save();

		if ( 'RedirectShopper' == $result_code ) {

			// redirect to process payment action via Web Component
			$result = array(
				'result'   => 'success',
				'redirect' => add_query_arg(
					array(
						WKWC_ADN_PREFIX . '_payment_method' => $this->payment_method_type(),
						WKWC_ADN_PREFIX . '_order_id' => $order->get_id(),
					),
					Wkwc_Adyen_Service_Util::get_checkout_url( $order )
				),
			);

		}

		return $result;
	}

	/**
	 * Get payment region based on a given country.
	 *
	 * @since 1.6.3
	 *
	 * @param string $country Country code.
	 * @param string $default Default country code. Default to 'us' or 'eu' if
	 *                        passed country is in EU union.
	 *
	 * @return string Payment region
	 */
	public static function get_payment_region_from_country( $country, $default = 'us' ) {
		switch ( $country ) {
			case 'GB':
			case 'US':
			case 'JP':
				$region = strtolower( $country );
				break;
			default:
				$region = $default;
				if ( in_array( $country, WC()->countries->get_european_union_countries(), true ) ) {
					$region = 'eu';
				}
		}

		if ( ! array_key_exists( $region, self::get_payment_regions() ) ) {
			$region = 'us';
		}

		return $region;
	}

	/**
	 * Get payment regions.
	 *
	 * @since 1.6.3
	 *
	 * @return array Payment regions
	 */
	public static function get_payment_regions() {
		return array(
			'eu' => __( 'Euro Region', 'wkwc-adyen' ),
			'gb' => __( 'United Kingdom', 'wkwc-adyen' ),
			'us' => __( 'United States', 'wkwc-adyen' ),
			'jp' => __( 'Japan', 'wkwc-adyen' ),
		);
	}

	/**
	 * Adds an array of fields to be displayed on the gateway's settings screen.
	 *
	 * @since 1.0.4
	 * @return void
	 */
	public function init_form_fields() {

		$is_enabled = parent::init_form_fields();

		if ( $is_enabled === false ) {
			return;
		}

		$desc = sprintf( __( '1. Register for a new Amazon Pay merchant account, or sign in with your existing Amazon Pay Seller Central credentials to complete the plugin upgrade and configuration', 'wkwc-adyen' ) ) . '</br>';

		if ( in_array( $this->payment_method_type(), array( 'amazonpay' ) ) ) {
			$this->form_fields = array_merge(
				$this->form_fields,
				array(
					'testmode'         => array(
						'title'   => __( 'Test mode', 'wkwc-adyen' ),
						'label'   => __( 'Enable/Disable', 'wkwc-adyen' ),
						'default' => 'yes',
						'type'    => 'checkbox',
					),
					'payment_region'   => array(
						'title'       => __( 'Payment Region', 'wkwc-adyen' ),
						'type'        => 'select',
						'description' => '',
						'default'     => self::get_payment_region_from_country( WC()->countries->get_base_country() ),
						'options'     => self::get_payment_regions(),
					),
					'merchant_id'      => array(
						'title'       => __( 'Merchant Id', 'wkwc-adyen' ),
						'type'        => 'text',
						'description' => $desc,
					),
					'store_id'         => array(
						'title'       => __( 'Store Id', 'wkwc-adyen' ),
						'type'        => 'text',
						'description' => __( 'Enter the Amazon Pay store ID to link transactions to your Amazon merchant account.', 'wkwc-adyen' ),
					),
					'public_key_id'    => array(
						'title'       => __( 'Public Key Id', 'wkwc-adyen' ),
						'type'        => 'text',
						'description' => __( 'Enter the Amazon Pay public key ID for secure transaction authentication.', 'wkwc-adyen' ),
					),
					'private_key_file' => array(
						'title'       => __( 'Private Key', 'wkwc-adyen' ),
						'type'        => 'file',
						'description' => __( 'This key is automatically generated when you connect your Amazon Pay merchant account through the Configure button, but it can also be created manually by logging into Seller Central and generating keys under the INTEGRATION - Central section.', 'wkwc-adyen' ),
						'desc_tip'    => true,
					),
				)
			);
		}
	}


	/**
	 * Get settings
	 *
	 * @param  string $key Key, if retrieving a single key.
	 *
	 * @return array|mixed
	 */
	public static function get_settings( $key = null ) {
		$settings_options_name = 'woocommerce_wkwc_adyen_amazonpay_settings';

		$settings = (array) get_option( $settings_options_name, array() );

		$default = array(
			'enabled'                         => 'yes',
			'title'                           => __( 'Amazon Pay', 'wkwc-adyen' ),
			'description'                     => __( 'Complete your payment using Amazon Pay!', 'wkwc-adyen' ),
			'merchant_id'                     => '',
			'store_id'                        => '',
			'public_key_id'                   => '',
			'seller_id'                       => '',
			'mws_access_key'                  => '',
			'secret_key'                      => '',
			'payment_region'                  => 'eu',
			'enable_login_app'                => 'no',
			'app_client_id'                   => '',
			'sandbox'                         => 'yes',
			'payment_capture'                 => 'no',
			'authorization_mode'              => 'async',
			'redirect_authentication'         => 'popup',
			'cart_button_display_mode'        => 'button',
			'button_type'                     => 'LwA',
			'button_size'                     => 'small',
			'button_color'                    => 'Gold',
			'button_language'                 => '',
			'debug'                           => 'no',
			'hide_button_mode'                => 'no',
			'amazon_keys_setup_and_validated' => '0',
			'subscriptions_enabled'           => 'no',
			'mini_cart_button'                => 'no',
			'product_button'                  => 'no',
			'alexa_notifications_support'     => 'no',
		);

		$settings = apply_filters( 'woocommerce_wkwc_adyen_amazonpay_settings', array_merge( $default, $settings ) );

		if ( is_null( $key ) ) {
			return $settings;
		} else {
			return isset( $settings[ $key ] ) ? $settings[ $key ] : null;
		}
	}
}
