<?php

namespace ChinaPayments\ThirdPartyIntegration\WooCommerce\Blocks\Stripe;

use ChinaPayments\PaymentGateway as CP_PaymentGateway;

class UnionPay extends Skeleton {

  protected $name = 'china_payments_stripe_unionpay';

  public function get_checkout_block_script_path() {
    return plugins_url(
      'interface/woocommerce-checkout-blocks/stripe/unionpay/build/index.js',
      CHINA_PAYMENTS_BASE_FILE_PATH
    );
  }

  public function get_payment_method_script_handles() {
    // Register Stripe.js first
    if ( ! wp_script_is( 'stripe-js-v3', 'registered' ) ) {
      wp_register_script(
        'stripe-js-v3',
        'https://js.stripe.com/v3/',
        array(),
        null,
        true
      );
    }

    // Register our block script with Stripe.js as an explicit dependency
    wp_register_script(
      'china-payments-' . $this->name . '-blocks-integration',
      $this->get_checkout_block_script_path(),
      array(
        'wc-blocks-registry',
        'wc-settings',
        'wp-element',
        'wp-html-entities',
        'stripe-js-v3'
      ),
      CHINA_PAYMENTS_VERSION,
      true
    );

    return array( 'china-payments-' . $this->name . '-blocks-integration' );
  }

  public function get_payment_method_data() {
    $data = parent::get_payment_method_data();

    try {
      $stripeIntegration = CP_PaymentGateway::get_integration_from_settings( 'stripe' );
      $data['stripe_publishable_key'] = $stripeIntegration->get_public_key();
    } catch ( \Exception $e ) {
      $data['stripe_publishable_key'] = '';
    }

    // REST endpoint for server-side payment verification (same as WeChat/Alipay flow)
    // The {ORDER_ID} placeholder is replaced by JS after checkout creates the order
    $data['payment_completed_url'] = rest_url( CHINA_PAYMENTS_REST_API_PREFIX . '/v1/third-party-integration/woocommerce/stripe-payment-completed/' );

    return $data;
  }

}
