<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model;

use Exception;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Api\PaymentsApi;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Configuration;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Model\PaymentsPayRequest;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Model\PaymentsPayRequestCustomerPaymentData;
use Simplyin\Simplyin_W_Plugin\Lib\Remote\SimplyInApi\Model\PaymentsPayRequestPaymentMethodData;
use Simplyin\Simplyin_W_Plugin\Lib\Session\Simplyin_Session;
use Simplyin\Simplyin_W_Plugin\Payments\Gateway\Gateway_Helper;

class Payment_Type_Card extends Abstract_Card_Payment implements Payment_Type_Interface {

	public function process_payment( Order_Data $order_data ) {
		global $simplyin_config;
		$simplyin_api_url    = $simplyin_config['backendSimplyIn'];
		$config              = new Configuration();
		$simplyin_auth_token = ( new Simplyin_Session() )->get( 'simplyin_auth_token' );
		if ( ! empty( $simplyin_auth_token ) ) {
			$config->setApiKey( 'api_token', $simplyin_auth_token );
		}

		$config->setApiKey( 'X-Auth-Merchant-Api-Key',
			get_option( 'simplyin_api_key' ) );
		$config->setHost( $simplyin_api_url );

		$api                = new PaymentsApi( null, $config );
		$this->payment_uuid = $this->generate_random_uuid();

		$order   = $order_data->get_order();
		$request = new PaymentsPayRequest();
		//$request->setOrderId( uniqid() );
		$request->setPaymentMethodId( $this->get_id() );
		$request->setPaymentId( $this->payment_uuid );
		$request->setTitle( 'Order #' . $order->get_id() );
		$request->setAmount( Gateway_Helper::normalize_price( $order->get_total() ) );
		$request->setCurrency( get_woocommerce_currency() );
		$request->setReturnUrl( $order->get_checkout_order_received_url() );
		$request->setWebhookUrl( Gateway_Helper::get_webhook_url( $order ) );

		$debug = [
			'PaymentId'       => $request->getPaymentId(),
			'PaymentMethodId' => $request->getPaymentMethodId(),
			'Title'           => $request->getTitle(),
			'Amount'          => $request->getAmount(),
			'Currency'        => $request->getCurrency(),
			'ReturnUrl'       => $request->getReturnUrl(),
			'WebhookUrl'      => $request->getWebhookUrl(),
		];

		if ( false === $this->is_simplyin_user_logged() ) {
			$customerPaymentData = new PaymentsPayRequestCustomerPaymentData();
			$customerPaymentData->setEmail( $order->get_billing_email() );
			$customerPaymentData->setId( '' );
			$customerPaymentData->setFirstName( $order->get_billing_first_name() );
			$customerPaymentData->setLastName( $order->get_billing_last_name() );
			$customerPaymentData->setPhone( $order->get_billing_phone() );
			$request->setCustomerPaymentData( $customerPaymentData );
		}


		try {
			$raw = $api->paymentsPay( $request );
		} catch ( Exception $e ) {

			$this->handle_error_customer_message( $e );
			$order_data->update_selected_payment_method( $this );

			simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
				sprintf( "[Payment_Type_Card] [process_payment] %s",
					wp_json_encode( [
						'error'   => $e->getMessage(),
						'request' => $debug,
					] ),
				),
				'payments' );

			throw new Exception( esc_html( $e->getMessage() ) );
		}

		$this->payment_status      = $raw->getStatus();
		$this->provider_payment_id = $raw->getProviderPaymentId();
		$this->registered_at       = $raw->getRegisteredAt();
		// For 3DS flows redirect_url may be present
		if ( method_exists( $raw, 'getRedirectUrl' ) ) {
			$this->redirect_url = $raw->getRedirectUrl();
		}

		$order_data->update_selected_payment_method( $this );

		simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
			sprintf( "[Payment_Type_Card] [process_payment] %s",
				wp_json_encode( [
					'request'      => $debug,
					'raw response' => $raw,
				] ),
			),
			'payments' );


	}


	public function configure_on_checkout() {

	}

	public function set_payment_status( string $payment_status ) {
		$this->payment_status = $payment_status;
	}
}
