<?php
/**
 * AnyCoin Blocks Support.
 *
 * @package AnyCoin_Payment_Gateway
 */

defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

/**
 * Blocks support integration for AnyCoin Payment Gateway.
 */
final class AnyCoin_Blocks_Support extends AbstractPaymentMethodType {

	/**
	 * Gateway instance used for supports detection.
	 *
	 * @var AnyCoin_Payment_Gateway|null
	 */
	private $gateway;

	/**
	 * Payment method name registered with Blocks.
	 *
	 * @var string
	 */
	protected $name = 'anycoin_payment';

	/**
	 * Initialize the payment method type.
	 */
	public function initialize() {
		$this->settings = get_option( 'woocommerce_anycoin_payment_settings', [] );

		$this->gateway = null;
		if ( function_exists( 'WC' ) ) {
			$wc = WC();
			if ( is_object( $wc ) && isset( $wc->payment_gateways ) && is_object( $wc->payment_gateways ) && method_exists( $wc->payment_gateways, 'payment_gateways' ) ) {
				$gateways      = $wc->payment_gateways->payment_gateways();
				$this->gateway = isset( $gateways[ $this->name ] ) ? $gateways[ $this->name ] : null;
			}
		}
	}

	/**
	 * Returns if this payment method should be active.
	 *
	 * @return boolean
	 */
	public function is_active() {
		return ! empty( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'];
	}

	/**
	 * Returns an array of scripts/handles to be registered for this payment method.
	 *
	 * @return array
	 */
	public function get_payment_method_script_handles() {
		wp_register_script(
			'wc-anycoin-blocks-integration',
			plugin_dir_url( __DIR__ ) . 'assets/js/blocks/anycoin-payment-blocks.js',
			[
				'wc-blocks-registry',
				'wc-settings',
				'wp-element',
				'wp-html-entities',
			],
			filemtime( plugin_dir_path( __DIR__ ) . 'assets/js/blocks/anycoin-payment-blocks.js' ),
			true
		);

		return [ 'wc-anycoin-blocks-integration' ];
	}

	/**
	 * Returns an array of key=>value pairs of data made available to payment methods script.
	 *
	 * @return array
	 */
	public function get_payment_method_data() {
		return [
			'title'       => $this->get_setting( 'title' ),
			'description' => $this->get_setting( 'description' ),
			'icon'        => ANYCOIN_PAYMENT_PLUGIN_URL . 'assets/images/zano-icon.png',
			'supports'    => $this->get_supported_features(),
		];
	}

	/**
	 * Get supported features for this payment method.
	 *
	 * @return array
	 */
	public function get_supported_features() {
		return $this->gateway ? array_filter( $this->gateway->supports, [ $this->gateway, 'supports' ] ) : [ 'products' ];
	}
}
