<?php
/**
 * This file handles Adyen Common Action

 * @package WK Adyen Checkout Api
 *
 * @version 1.0.0
 */

namespace WkwcAdyen\Helper\Common;

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

use WkwcAdyen\Helper\Adyen\Wkwc_Adyen_Helper;

if ( ! class_exists( 'Wkwc_Adyen_Checkout_Action' ) ) {

	/**
	 * Users class.
	 */
	class Wkwc_Adyen_Checkout_Action {

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

		/**
		 * Checkout base url
		 *
		 * @var $base_url
		 */
		public $base_url;

		/**
		 * $api_handler
		 *
		 * @var Wkwc_Adyen_Api_Handler
		 */
		public $api_handler;

		/**
		 * Adyen Config Instance
		 *
		 * @var Wkwc_Adyen_Config
		 */
		public $adyen_config;

		/**
		 * Version of the API.
		 *
		 * @var string
		 */
		protected $version = 'v71';

		/**
		 * Adyen constructor.
		 *
		 * @param Wkwc_Adyen_Config $adyen_config .
		 */
		public function __construct() {
			$this->adyen_helper = new Wkwc_Adyen_Helper();
			$this->adyen_config = $this->adyen_helper->adyen_config;
			$this->base_url     = $this->wkwc_adyen_checkout_base_url();

			$this->api_handler = new Wkwc_Adyen_Api_Handler( $this->base_url );
		}



		/**
		 * Base of the URL.
		 *
		 * @param string $endpoint
		 * @return string
		 */
		public function wkwc_adyen_checkout_base_url() {

			$url = 'https://' . $this->adyen_config->wkwc_adyen_get_live_endpoint_prefix() . '-checkout-live.' . $this->adyen_helper->wkwc_adyen_get_live_domain() . '/checkout/' . $this->version;

			if ( $this->adyen_config->wkwc_adyen_is_test_mode() ) {
				$url = 'https://checkout-test.' . $this->adyen_helper->wkwc_adyen_get_test_domain() . '/' . $this->version;
			}

			return $url;
		}

		/**
		 * Retrieves the entire list of payment methods.
		 *
		 * @param string $country
		 * @param float  $amount
		 * @param bool   $cached - whether or not to use cached data
		 * @return array
		 */
		public function list_payment_methods( $country = null, float $amount = 0, $cached = true ) {

			$result = array();

			if ( $cached ) {
				$result = get_transient( WKWC_ADN_PREFIX . '_payment_methods_' . $country );
			}

			if ( empty( $result ) ) {

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

				if ( ! is_null( $country ) ) {

					$payload = array_merge(
						$payload,
						array(
							'countryCode' => $country,
							'amount'      => array(
								'currency' => get_woocommerce_currency(),
								'value'    => $this->wkwc_adyen_format_amount( $amount ),
							),
						)
					);
				}

				$response = $this->api_handler->wkwc_adyen_remote_post( 'paymentMethods', $payload );

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

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

					set_transient( WKWC_ADN_PREFIX . '_payment_methods_' . $country, $result, \DAY_IN_SECONDS );

				}
			}

			return $result;
		}

		/**
		 * Retrieves the available stored payment methods.
		 *
		 * @param string $country
		 * @param float  $amount
		 * @return array
		 */
		public function get_stored_payment_methods( $country = null, float $amount = 0 ) {

			$reference = $this->adyen_helper::get_shopper_reference();
			$result    = array_filter( (array) get_transient( 'wkwc_adyen_stored_payment_methods_' . $reference ) );

			if ( empty( $result ) && is_user_logged_in() ) {

				$response = $this->list_payment_methods( $country, $amount, false );

				if ( isset( $response['storedPaymentMethods'] ) ) {

					$result = $response['storedPaymentMethods'];

					set_transient( 'wkwc_adyen_stored_payment_methods_' . $reference, $result, DAY_IN_SECONDS );
				}
			}

			return $result;

		}

		/**
		 * Get Payment Method
		 *
		 * @param string $amount .
		 *
		 * @return mixed
		 */
		public function wkwc_adyen_get_payment_methods( $country = null, float $amount = 0 ) {
			$result   = array();
			$response = $this->list_payment_methods( $country, $amount );

			if ( isset( $response['paymentMethods'] ) ) {
				$result = $response['paymentMethods'];
			}

			return $result;
		}


		/**
		 * Retrieves the available card types.
		 *
		 * @param string $country
		 * @return array
		 */
		public function get_card_types( $country = null ) {
			$result   = array();
			$response = $this->list_payment_methods( $country );

			if ( isset( $response['paymentMethods'] ) ) {

				foreach ( $response['paymentMethods'] as $item ) {
					if ( $item['type'] == 'scheme' ) {
						$result = $item['brands'];
					}
				}
			}

			return $result;
		}

		/**
		 * Retrieves the stored cards which have `Ecommerce` support.
		 *
		 * @param string  $country
		 * @param integer $amount
		 * @return array
		 */
		public function get_ec_stored_cards( $country = null, float $amount = 0 ) {

			$result = array();
			$list   = $this->get_stored_payment_methods( $country, $amount );

			foreach ( $list as $item ) {
				if ( isset( $item['lastFour'] ) && in_array( 'Ecommerce', $item['supportedShopperInteractions'] ) ) {
					$result[] = $item;
				}
			}

			return $result;

		}

		/**
		 * Sends a payment.
		 *
		 * @param array $payload
		 * @return object
		 */
		public function send_payment( $payload ) {

			$payload = array_merge( $payload, $this->adyen_helper->wkwc_adyen_app_info(), $this->adyen_helper->wkwc_adyen_capture_immediately() ); // add our app info in the payload

			$response = $this->api_handler->wkwc_adyen_remote_post( 'payments', $payload );

			return $response;

		}

		/**
		 * Sends the payment details.
		 *
		 * @param array $payload
		 * @return object
		 */
		public function send_payment_details( $payload ) {

			$response = $this->api_handler->wkwc_adyen_remote_post( 'payments/details', $payload );

			return $response;

		}



		/**
		 * Refunds a payment.
		 *
		 * @param string $reference - payment reference to be refunded
		 * @param float  $amount
		 * @return object
		 */
		public function refund_payment( $reference, $amount ) {

			$payload = array(
				'amount'          => array(
					'currency' => get_woocommerce_currency(),
					'value'    => $this->adyen_helper->wkwc_adyen_format_amount( $amount ),
				),
				'merchantAccount' => $this->adyen_config->wkwc_adyen_get_merchantcode(),
				'reference'       => $reference,
			);

			$response = $this->api_handler->wkwc_adyen_remote_post( "payments/{$reference}/refunds", $payload );

			return $response;

		}


		/**
		 * Cancels the payment.
		 *
		 * @param string $reference - payment reference to be canceled
		 * @return object
		 */
		public function cancel_payment( $reference ) {

			$payload = array(
				'merchantAccount' => $this->adyen_config->wkwc_adyen_get_merchantcode(),
				'reference'       => $reference,
			);

			$response = $this->api_handler->wkwc_adyen_remote_post( "payments/{$reference}/cancels", $payload );

			return $response;

		}



		/**
		 * Captures an authorised payment.
		 *
		 * @param string $reference - payment reference to be captured
		 * @param float  $amount
		 * @return object
		 */
		public function capture_payment( $reference, $amount ) {

			$payload = array(
				'amount'          => array(
					'currency' => get_woocommerce_currency(),
					'value'    => $this->adyen_helper->wkwc_adyen_format_amount( $amount ),
				),
				'merchantAccount' => $this->adyen_config->wkwc_adyen_get_merchantcode(),
				'reference'       => $reference,
			);

			$response = $this->api_handler->wkwc_adyen_remote_post( "payments/{$reference}/captures", $payload );

			return $response;

		}

		/**
		 * Get payment links details by id.
		 *
		 * @param string $link_id - payment link id
		 * @return object
		 */
		public function payment_link_details( $link_id ) {

			$response = $this->api_handler->wkwc_adyen_remote_get( "paymentLinks/{$link_id}" );

			return $response;
		}

		/**
		 * Create session apple pay
		 *
		 * @param object $order
		 *
		 * @return mixed
		 */
		public function create_session_for_apple_pay( \WC_Order $order, $reference ) {

			$api_url = 'https://checkout-test.adyen.com/checkout/v64/applePay/sessions';

			$payload = array(
				'displayName'        => 'WebkulSoftwareCOM',
				'domainName'         => $_SERVER['HTTP_HOST'],
				'merchantIdentifier' => $this->adyen_config->wkwc_adyen_get_merchantcode(),
			);

			// Set up arguments for the request
			$args = array(
				'method'  => 'POST',
				'headers' => $this->api_handler->wkwc_adyen_remote_headers(),
				'body'    => wp_json_encode( $payload ),
			);

			// Execute the request
			$response = wp_remote_request( $api_url, $args );

			return $response;
		}

	}

}
