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

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

/**
 * Title: PhonePe for Business Gateway
 * Copyright: 2020-2026 Knit Pay
 *
 * @author Knit Pay
 * @version 1.0.0
 * @since 1.0.0
 */
class Gateway extends KnitPayUPIGateway {

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

		$this->merchant_verified = true; // TODO: Implement merchant verification logic
	}
	
	/**
	 * Start.
	 *
	 * @see KnitPayUPIGateway::start()
	 *
	 * @param Payment $payment
	 *            Payment.
	 */
	public function start( Payment $payment ) {
		parent::start( $payment );
		
		$result = $this->get_gateway_data(
			$payment,
			[
				'mid' => $this->config->mid,
			]
		);

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

	/**
	 * Update status of the specified payment.
	 *
	 * @param Payment $payment Payment.
	 */
	public function update_status( Payment $payment ) {
		parent::update_status( $payment );

		$order_status = API::get_order_status( $payment->get_meta( 'paytm_data' ) );

		if ( property_exists( $order_status, 'STATUS' ) && 'TXN_SUCCESS' === $order_status->STATUS ) {
			if ( $order_status->TXNAMOUNT !== $payment->get_total_amount()->number_format( null, '.', '' ) ) {
				$payment->set_status( PaymentStatus::FAILURE );
				return;
			}

			$payment->set_transaction_id( $order_status->BANKTXNID );

			$payment->set_status( Core_Statuses::SUCCESS );
			$payment->add_note( '<strong>Paytm Response:</strong><br><pre>' . print_r( $order_status, true ) . '</pre><br>' );
		} else {
			$this->expire_old_upi_payment( $payment );
		}
	}
}
