<?php

namespace ChinaPayments\ThirdPartyIntegration\WooCommerce\Gateway\Stripe;

use WC_Order;
use ChinaPayments\PaymentGateway as CP_PaymentGateway;

class UnionPay extends Skeleton {

	public $id         = 'china_payments_stripe_unionpay';
	public $has_fields = false;

	public function __construct() {
		$this->method_title       = sprintf( __( '%s - UnionPay', 'wp-stripe-global-payments' ), CHINA_PAYMENTS_NAME );
		$this->method_description = __( 'Accept UnionPay card payments using your Stripe account.', 'wp-stripe-global-payments' );
		$this->icon               = plugins_url( 'interface/img/payment-gateway/payment-method-unionpay.svg', CHINA_PAYMENTS_BASE_FILE_PATH );

		parent::__construct();

		// Verify payment on order-received page to avoid webhook race condition
		add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'verify_payment_on_thankyou' ), 1 );
	}

	public function default_name() {
		return 'UnionPay';
	}

	public function get_supported_currencies() {
		return apply_filters(
			'china_payments_woocommerce_stripe_unionpay_currencies',
			array(
				'CNY',
				'AUD',
				'CAD',
				'EUR',
				'GBP',
				'HKD',
				'JPY',
				'NZD',
				'SGD',
				'USD',
			)
		);
	}

	public function get_stripe_payment_method_alias() {
		return 'card';
	}

	/**
	 * Override process_payment for inline card confirmation.
	 * Uses 'china-payments-confirm-card' instead of 'china-payments-intent-id'
	 * so that _handle_payment_flow() does NOT trigger on redirect.
	 * The JS will intercept this redirect, confirm payment client-side,
	 * then redirect to the order-received page.
	 */
	public function process_payment( $order_id ) {
		$order_id = (int) $order_id;
		$order    = new WC_Order( $order_id );

		$payment_intent_information = $this->get_payment_intent_information( $order );

		if ( is_wp_error( $payment_intent_information ) ) {
			$code = $payment_intent_information->get_error_code();
			if ( ! is_numeric( $code ) ) {
				$code = 400;
			}
			throw new \Exception( $payment_intent_information->get_error_message(), $code );
		}

		// Build redirect URL with:
		// - china-payments-confirm-card=1 (NOT china-payments-intent-id, to avoid triggering payment handler)
		// - china-payments-intent-secret (for JS to use with stripe.confirmCardPayment)
		// - china-payments-return (order-received URL for post-confirmation redirect)
		$redirect_url = add_query_arg( array(
			'china-payments-confirm-card'  => '1',
			'china-payments-intent-secret' => $payment_intent_information['payment_intent_secret'],
			'china-payments-return'        => urlencode( $this->get_return_url( $order ) ),
		), $this->get_payment_redirect_base( $order ) );

		return array(
			'result'   => 'success',
			'redirect' => $redirect_url,
		);
	}

	/**
	 * Verify payment with Stripe when the order-received page loads.
	 * This ensures the order is marked as paid even if the webhook hasn't fired yet,
	 * eliminating the race condition where the "Pay" button briefly appears.
	 *
	 * @param int $order_id
	 */
	public function verify_payment_on_thankyou( $order_id ) {
		$order = wc_get_order( $order_id );

		if ( ! $order || $order->is_paid() ) {
			return;
		}

		$payment_intent_id = $order->get_meta( 'china_payments_payment_intent_id' );

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

		try {
			$stripeIntegration = CP_PaymentGateway::get_integration_from_settings( 'stripe' );
			$payment_intent    = $stripeIntegration->stripeClient()->paymentIntents->retrieve( $payment_intent_id );

			if ( $payment_intent->status === 'succeeded' ) {
				$order->payment_complete( $payment_intent->id );
			}
		} catch ( \Exception $e ) {
			// Don't break the thank you page — webhook will handle it eventually
			error_log( '[China Payments] UnionPay thankyou verification failed: ' . $e->getMessage() );
		}
	}

	public function init_form_fields() {
		parent::init_form_fields();

		$this->form_fields['title']['default']       = __( 'UnionPay', 'wp-stripe-global-payments' );
		$this->form_fields['description']['default'] = __( 'Pay with your UnionPay card.', 'wp-stripe-global-payments' );
	}
}
