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

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

/**
 * Title: HDFC SmartHub Vyapar Gateway
 * Copyright: 2020-2026 Knit Pay
 *
 * @author Knit Pay
 * @version 1.4.0.0
 * @since 1.4.0.0
 */
class Gateway extends KnitPayUPIGateway {
	private $api;

	/**
	 * Constructs and initializes an HDFC SmartHub Vyapar 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 );
		$this->merchant_verified = true; // TODO: Implement merchant verification logic
	}

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

		$method = new PaymentMethod( PaymentMethods::UPI_COLLECT );

		$field_customer_upi_id = new TextField( 'knit_pay_customer_upi_id' );
		$field_customer_upi_id->set_label( __( 'UPI ID', 'knit-pay-lang' ) );
		$field_customer_upi_id->set_required( true );
		$field_customer_upi_id->meta_key = 'customer_upi_id';

		$method->add_field( $field_customer_upi_id );
		$this->register_payment_method( $method );

		if ( defined( 'KnitPay\Gateways\PaymentMethods::SMS_PAYMENT_LINK' ) ) {
			$this->register_payment_method( new PaymentMethod( PaymentMethods::SMS_PAYMENT_LINK ) );
		}
	}

	/**
	 * Start.
	 *
	 * @see KnitPayUPIGateway::start()
	 *
	 * @param Payment $payment
	 *            Payment.
	 */
	public function start( Payment $payment ) {
		parent::start( $payment );
		
		// Check connection.
		if ( '' === $this->config->tid ) {
			throw new Exception( 'HDFC SmartHub Vyapar is not connected' );
		}
		
		try {
			$knit_pay_upi_data         = $this->knit_pay_upi_data( $payment );
			$knit_pay_upi_data['data'] =
			wp_parse_args(
				$knit_pay_upi_data['data'],
				[
					'tid' => $this->config->tid,
				]
			);

			$result = $this->api->encrypt_key_rapid( $knit_pay_upi_data, true );

			$payment->set_meta( 'hdfc_smarthub_key', $result->data->hdfc_smarthub_data->encryption_key );
			$payment->set_meta( 'kpp_charge_id', $result->id );
		} catch ( Exception $e ) {
			throw new Exception( $e->getMessage() );
		}

		$hdfc_payment_data = [
			'terminalId'  => $this->config->tid,
			'amount'      => $payment->get_total_amount()->number_format( null, '.', '' ),
			'description' => $payment->get_description(),
			'appTxnid'    => $payment->get_transaction_id(),
			'pgId'        => 1,
		];

		if ( PaymentMethods::UPI_COLLECT === $payment->get_payment_method() ) {
			$hdfc_payment_data['payerVpa'] = $payment->get_meta( 'customer_upi_id' );
			$payment_resonse_data          = $this->api->init_upi_collect( $hdfc_payment_data, $payment->get_meta( 'hdfc_smarthub_key' ) );
		} elseif ( PaymentMethods::SMS_PAYMENT_LINK === $payment->get_payment_method() ) {
			$hdfc_payment_data['customerMobileNumber'] = $payment->get_billing_address()->get_phone();
			$payment_resonse_data                      = $this->api->init_sms_pay( $hdfc_payment_data, $payment->get_meta( 'hdfc_smarthub_key' ) );
		} else {
			$payment_resonse_data = $this->api->init_qr_pay( $hdfc_payment_data, $payment->get_meta( 'hdfc_smarthub_key' ) );

			$payment->set_meta( 'qr_text', $payment_resonse_data->qr_text );
		}

		$payment->set_transaction_id( $payment_resonse_data->mTxnid );
		$payment->set_meta( 'hdfc_smarthub_key', $payment_resonse_data->encyption_key_data );
	}
	
	public function get_upi_qr_text( $payment ) {
		return $payment->get_meta( 'qr_text' );
	}

	public function update_status( Payment $payment ) {
		if ( PaymentMethods::UPI_COLLECT === $payment->get_payment_method() ) {
			$this->payment_expiry_recheck_seconds = 10800;
		}
		return parent::update_status( $payment );
	}

	protected function get_bulk_transaction_data( Payment $payment ) {
		if ( '' === $this->config->session_id ) {
			throw new Exception( 'HDFC SmartHub Vyapar is not connected' );
		}

		$check_status_count = isset( $_POST['check_status_count'] ) ? sanitize_text_field( $_POST['check_status_count'] ) : '0';
		$check_status_count = intval( $check_status_count );
		if ( $check_status_count % 3 === 0 ) {
			$transaction_data = $this->api->get_transaction_details( $payment->get_date(), $payment->get_meta( 'hdfc_smarthub_key' ) );
		} else {
			$transaction_data = $this->api->get_mini_statement( $payment->get_meta( 'hdfc_smarthub_key' ) );
		}

		if ( 'Success' !== $transaction_data->status ) {
			return;
		}
		
		$transactions = [];
		foreach ( $transaction_data->transactionParams as $transaction ) {
			if ( ! property_exists( $transaction, 'status' ) ) {
				continue;
			}

			$transactions[] = [
				'kp_transaction_id' => $transaction->txnid,
				'utr'               => $transaction->issuerRefNo,
				'amount'            => $transaction->amount,
				'status'            => Statuses::transform( $transaction ),
				'provider_response' => $transaction,
			];
		}

		return $transactions;
	}

	protected function before_bulk_update_save( Payment $payment, $transaction ) {
		if ( Core_Statuses::OPEN !== $payment->get_status() ) {
			$payment->delete_meta( 'hdfc_smarthub_key' );
			$payment->delete_meta( 'qr_text' );
		}
	}
}
