<?php
/**
 * File that define P24_Payment_Method class.
 *
 * @package Przelewy24
 */

defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use Automattic\WooCommerce\StoreApi\Payments\PaymentContext;
use Automattic\WooCommerce\StoreApi\Payments\PaymentResult;

/**
 * The class for payment for the block style.
 */
class P24_Payment_Method extends AbstractPaymentMethodType {

	/**
	 * The base path for the plugin entry point.
	 *
	 * @var string
	 */
	private $base_path;

	/**
	 * The plugin core.
	 *
	 * @var P24_Core
	 */
	private $plugin_core;

	/**
	 * The constructor.
	 *
	 * @param P24_Core $plugin_core The core of plugin.
	 * @param string   $base_path The base patch for the plugin entry point.
	 */
	public function __construct( P24_Core $plugin_core, $base_path ) {
		$this->plugin_core = $plugin_core;
		$this->base_path   = $base_path;

		$this->name = WC_Gateway_Przelewy24::PAYMENT_METHOD;
	}

	/**
	 * Add all listeners.
	 *
	 * @return void
	 */
	public function initialize() {
		add_action( 'woocommerce_rest_checkout_process_payment_with_context', array( $this, 'try_process_request' ), 10, 2 );
	}

	/**
	 * Try process request.
	 *
	 * @param PaymentContext $context Provided context.
	 * @param PaymentResult  $result Provided result, to update.
	 * @return void
	 */
	public function try_process_request( PaymentContext $context, PaymentResult $result ) {
		if ( $context->payment_method !== $this->name ) {
			/* Nothing to do. */
			return;
		}
		$converter = $this->plugin_core->get_rest_converter_transaction();
		$payload   = $converter->generate_payload_for_rest( $context->order );
		$config    = $this->plugin_core->get_config_for_currency( $context->order->get_currency() );
		$api_rest  = new P24_Rest_Transaction( $config );
		$token     = $api_rest->register_raw_token( $payload );

		if ( isset( $token ) ) {
			$legacy_class = new Przelewy24Class( $config );
			$result->set_status( 'success' );
			$url = $legacy_class->trnRequest( $token, false );
			$result->set_redirect_url( $url );
		} else {
			$result->set_status( 'error' );
		}
	}

	/**
	 * Gets an array of all registered payment method script handles, but only for active payment methods.
	 *
	 * @return string
	 */
	public function get_payment_method_script_handles() {
		$script_code_name = 'p24-checkout-js';
		$script_info      = require __DIR__ . '/../assets/js/checkout.asset.php';

		wp_register_script(
			$script_code_name,
			$this->base_path . '/assets/js/checkout.js',
			$script_info['dependencies'],
			$script_info['version'],
			true
		);

		return array( $script_code_name );
	}

	/**
	 * An array of key, value pairs of data made available to payment methods client side.
	 *
	 * @return array
	 */
	public function get_payment_method_data() {
		return array(
			'gateway_name' => $this->name,
			'gateway_text' => __( 'Zapłać z Przelewy24', 'przelewy24' ),
		);
	}
}
