<?php /** @noinspection PhpMultipleClassDeclarationsInspection */

namespace WeeConnectPay\WordPress\Plugin\includes;

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use Exception;
use WC_Gateway_Weeconnectpay;
use WeeConnectPay\Environment;
use WeeConnectPay\Exceptions\SettingsInitializationException;
use WeeConnectPay\Integrations\GoogleRecaptcha;
use WeeConnectPay\Integrations\IntegrationSettings;
use WeeConnectPay\Integrations\LogService;
use WeeConnectPay\Integrations\PaymentFields;
// error_log( 'in WooCommerce Blocks gateway class file' );

class WeeConnectPayMethod extends AbstractPaymentMethodType {

	/**
	 * @var $name string
	 */
	protected $name = 'weeconnectpay';

	/**
	 * Constructor
	 */
	public function __construct() {
	}

	public function initialize(): void {
	}

	public function is_active(): bool {
		// return $this->gateway->is_available();
		return true;
	}

	public function get_payment_method_script_handles(): array {

		$cloverSdkScriptName = 'weeconnectpay-clover-sdk-js';

		$cloverSdkUrl = Environment::getCloverSdkUrl();
		wp_register_script( $cloverSdkScriptName, $cloverSdkUrl, array(), null, true ); // not versioned because we don't control the versioning of this script

		$paymentFieldsStyleName = 'weeconnectpay-payment-fields-css';
		wp_register_style( $paymentFieldsStyleName, WEECONNECTPAY_PLUGIN_URL . 'site/css/weeconnect-public.css', array(), WEECONNECT_VERSION );
		wp_enqueue_style( $paymentFieldsStyleName, '', array(), WEECONNECT_VERSION );

		// The Classic path's `PaymentFields::registerScripts()` registers the
		// same SDK web-component bundle handle — register it here too so the
		// Blocks adapter can depend on it regardless of which entrypoint loads
		// first.
		$paymentFieldsSdk = 'weeconnectpay-payment-fields-sdk';
		wp_register_script( $paymentFieldsSdk, WEECONNECTPAY_PLUGIN_URL . 'packages/payment-fields/dist/web-component/index.js', array( $cloverSdkScriptName ), WEECONNECT_VERSION, true );
		$paymentFieldsBlocks = 'weeconnectpay-blocks-payment-fields-js';
		wp_register_script( $paymentFieldsBlocks, WEECONNECTPAY_PLUGIN_URL . 'payment-fields-blocks/assets/js/frontend/blocks.js', array( $cloverSdkScriptName, $paymentFieldsSdk ), wp_rand(), true );

		// Both bundles are ESM (tsup/webpack default). Mark them as
		// `type="module"` so the browser parses the `import` syntax. Filter
		// is idempotent.
		PaymentFields::registerModuleScriptFilter();

		$handles = array( $cloverSdkScriptName, $paymentFieldsSdk, $paymentFieldsBlocks );

		$googleRecaptchaScriptHandle = 'weeconnectpay-google-recaptcha';
		if ( GoogleRecaptcha::isEnabledAndReady() ) {
			// No dependencies, the only time we use it is onPaymentSetup, which gives a chance for EVERYTHING to load
			wp_register_script( $googleRecaptchaScriptHandle, GoogleRecaptcha::getSdkSrc(), array(), WEECONNECT_VERSION, true );
			$handles[] = $googleRecaptchaScriptHandle;
		}

		return $handles;
	}

	// public function get_payment_method_script_handles_for_admin(): array {
	// return [];
	// }

	public function get_payment_method_data(): array {

		$integrationSettings = new IntegrationSettings();

		try {
			global $woocommerce;
			$cartTotalCents = isset( $woocommerce->cart ) ? (int) round( $woocommerce->cart->total * 100 ) : 0;

			$gatewayWcSettingsData = array(
				'clover'          => array(
					'pakms'            => $integrationSettings->getPublicAccessKey(),
					'locale'           => WeeConnectPayUtilities::getLocale(),
					'merchantId'       => $integrationSettings->getCloverMerchant()->getUuid(),
					'cartTotal'        => $cartTotalCents,
					'currency'         => get_woocommerce_currency(),
					'cloverSdkUrl'     => Environment::getCloverSdkUrl(),
					'googlePayEnabled' => $integrationSettings->getGooglePayOrDefault() === '1',
					'threeDSecure' => array(
						'enabled' => $integrationSettings->getThreeDSecureBetaOrDefault() === '1',
						'sdkUrl'  => Environment::getClover3DSSdkUrl(),
						// Endpoint + REST nonce the Blocks side calls after the
						// browser completes the method/challenge step (WSO-9 Half B).
						'finalizeUrl' => rest_url( 'weeconnectpay/v1/woocommerce/3ds/finalize' ),
						'restNonce'   => wp_create_nonce( 'wp_rest' ),
					),
				),
				'branding'        => array(
					// Trust footer assets re-used from the existing PHP template (verbatim).
					'lockIconSrc'   => WEECONNECTPAY_PLUGIN_URL . 'site/img/lock.svg',
					'trustLogosSrc' => WEECONNECTPAY_PLUGIN_URL . 'site/img/secured-by-logos.png',
				),
				'woocommerce'     => array(
					'gateway' => array(
						'supports' => array(
							'products',
							'refunds',
							'subscriptions',
							'subscription_cancellation',
							'subscription_suspension',
							'subscription_reactivation',
							'subscription_amount_changes',
							'subscription_date_changes',
							'subscription_payment_method_change',
							'subscription_payment_method_change_customer',
						//	'subscription_payment_method_change_admin',
							'multiple_subscriptions',
						),
						'title'    => $integrationSettings->getWoocommerceGatewayTitle(),
					),
				),
				'wordpress'       => array(
					'locale' => WeeConnectPayUtilities::getLocale(),
				),
				'googleRecaptcha' => array(
					'isEnabled' => $integrationSettings->getGoogleRecaptchaOrDefault(),
					'siteKey'   => $integrationSettings->getGoogleRecaptchaSiteKeyOrDefault(),
				),
			);

			// error_log( 'gatewayWcSettingsData: '.json_encode( $gatewayWcSettingsData) );

			return $gatewayWcSettingsData;

		} catch ( SettingsInitializationException $e ) {
			LogService::error( 'SettingsInitializationException in get_payment_method_data: ' . $e->getMessage() );

			return array();
		} catch ( Exception $exception ) {
			LogService::error( 'Exception in get_payment_method_data: ' . $exception->getMessage() );

			return array();
		}
	}
}
