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

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

/**
 * Title: Tata Neu Business Gateway
 * Copyright: 2020-2025 Knit Pay
 *
 * @author Knit Pay
 * @version 1.9.0.0
 * @since 1.9.0.0
 */
class Gateway extends KnitPayUPIGateway {
	private $client;

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

		$this->add_support( 'bulk_payment_status_request' );

		$this->client = new Client( $config );
	}
	
	/**
	 * 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' => 'order_history',
			]
		);

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

	protected function register_payment_methods() {
		parent::register_payment_methods();

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

	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 ) {
		$tata_neu_data = $payment->get_meta( 'tata_neu_data' );
		if ( ! wp_doing_ajax() ) {
			$tata_neu_data                 = json_decode( $tata_neu_data );
			$tata_neu_data->recordsPerPage = 200;
			$tata_neu_data                 = wp_json_encode( $tata_neu_data );
		}
		$tata_neu_transactions = $this->client->get_order_history( $tata_neu_data );

		$transactions = [];
		foreach ( $tata_neu_transactions as $tata_neu_transaction ) {
			if ( 'CREDIT' !== $tata_neu_transaction->transactionType ) {
				continue;
			}

			switch ( $tata_neu_transaction->orderStatus ) {
				case 'Success':
					$status = PaymentStatus::SUCCESS;
					break;
				case 'Failed':
					$status = PaymentStatus::FAILURE;
					break;
				default:
					$status = PaymentStatus::OPEN;
					break;
			}
			
			$transactions[] = [
				'kp_transaction_id' => $tata_neu_transaction->remarks,
				'utr'               => $tata_neu_transaction->utr,
				'amount'            => $tata_neu_transaction->orderAmount,
				'status'            => $status,
				'provider_response' => $tata_neu_transaction,
			];
		}

		return $transactions;
	}
}
