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

use KnitPayUPI\Gateways\UpiQR\KnitPayUPIGateway;
use Pronamic\WordPress\Pay\Payments\Payment;

/**
 * Title: FreeCharge Gateway
 * Copyright: 2020-2026 Knit Pay
 *
 * @author Knit Pay
 * @version 1.7.0.0
 * @since 1.7.0.0
 */
class Gateway extends KnitPayUPIGateway {
	private $api;

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

		$this->add_support( 'bulk_payment_status_request' );

		$this->api = new API( $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->api->check_connection();

		$result = $this->get_gateway_data(
			$payment,
			[
				'request_type' => 'transaction_history',
			]
		);

		$payment->set_meta( 'freecharge_data', $result->data->freecharge_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 ) {
		$transaction_history = $this->api->get_transaction_history( $payment->get_meta( 'freecharge_data' ) );
		if ( empty( $transaction_history->globalTransactions ) ) {
			return;
		}

		$kp_transactions = [];
		foreach ( $transaction_history->globalTransactions as $freecharge_transaction ) {
			$fc_txn_details = $freecharge_transaction->txnDetails;
			if ( 'CREDIT' !== $fc_txn_details->paymentDirection ) {
				continue;
			}
			
			$kp_transaction_data = [
				'amount' => $fc_txn_details->amount,
				'status' => Statuses::transform( $fc_txn_details->status ),
			];

			$payment_information_details = $freecharge_transaction->billerInfo->billerMetaData[1]->sectionDetails;
			foreach ( $payment_information_details as $detail ) {
				if ( 'Comments' === $detail->name ) {
					$kp_transaction_data['kp_transaction_id'] = $detail->value;
				} elseif ( 'UPI Transaction ID' === $detail->name ) {
					$kp_transaction_data['utr'] = $detail->value;
				}
			}
			
			$kp_transaction_data['provider_response'] = $freecharge_transaction;

			$kp_transactions[] = $kp_transaction_data;
		}

		return $kp_transactions;
	}
}
