<?php
namespace KnitPayUPI\Gateways\UpiQR\GpayBiz;

use KnitPayUPI\Gateways\UpiQR\KnitPayUPIGateway;
use Pronamic\WordPress\Http\Facades\Http;
use Pronamic\WordPress\Pay\Payments\Payment;
use Pronamic\WordPress\Pay\Payments\PaymentStatus;
use Pronamic\WordPress\Pay\Payments\PaymentStatus as Core_Statuses;
use Exception;
use Pronamic\WordPress\Pay\Core\PaymentMethod;
use KnitPay\Gateways\PaymentMethods;

/**
 * Title: Google Pay Business Gateway
 * Copyright: 2020-2026 Knit Pay
 *
 * @author Knit Pay
 * @version 1.8.0.0
 * @since 1.8.0.0
 */
class Gateway extends KnitPayUPIGateway {
	private $client;

	/**
	 * Constructs and initializes an Google Pay Business gateway
	 *
	 * @param Config $config
	 *            Config.
	 */
	public function __construct( Config $config ) {     
		parent::__construct( $config );

		$this->add_support( 'bulk_payment_status_request' );

		$this->merchant_verified = true; // TODO: Implement merchant verification logic

		$this->client = new Client( $config );
	}
	
	protected function register_payment_methods() {
		parent::register_payment_methods();

		$this->register_payment_method( new PaymentMethod( PaymentMethods::UPI_INTENT_PHONEPE ) );
	}

	/**
	 * Start.
	 *
	 * @see KnitPayUPIGateway::start()
	 *
	 * @param Payment $payment
	 *            Payment.
	 */
	public function start( Payment $payment ) {
		parent::start( $payment );
		$transaction_id = preg_replace( '/[^a-zA-Z0-9\s]/', '', $payment->get_transaction_id() );
		$payment->set_transaction_id( $transaction_id );

		// Check connection.
		$this->client->check_connection();

		$result = $this->get_gateway_data(
			$payment,
			[
				'request_type' => 'transaction_details',
				'mid'          => $this->config->merchant_id,
			]
		);

		$payment->set_meta( 'gpay_biz_data', $result->data->gpay_biz_data );
		$payment->set_meta( 'kpp_charge_id', $result->id );
	}

	public function get_output_fields( Payment $payment ) {
		$data = parent::get_output_fields( $payment );

		$data['tn'] = $data['tr'];

		return $data;
	}

	protected function get_bulk_transaction_data( Payment $payment ) {
		$transactions = $this->client->get_transaction_details( $payment->get_meta( 'gpay_biz_data' ) );

		return $transactions;
	}
}
