<?php

namespace KnitPayUPI\Gateways\UpiQR\Mobikwik;

use Pronamic\WordPress\Http\Facades\Http;
use Exception;

/**
 * Title: MobiKwik API Client
 * Copyright: 2020-2026 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.6.0.0
 * @since   1.6.0.0
 */
class Client {
	const CONNECTION_TIMEOUT = 10;

	private $token;

	public function __construct( Config $config ) {
		$this->token = $config->token;
	}

	public function get_wallet_history( $mobikwik_data ) {
		if ( '' === $this->token ) {
			throw new Exception( 'MobiKwik is not connected.' );
		}

		$response = wp_remote_get(
			'https://webapi.mobikwik.com/p/wallet/history/v3',
			[
				'body'    => $mobikwik_data,
				'headers' => [
					'Authorization' => $this->token,
					'X-MClient'     => '0',
				],
				'timeout' => self::CONNECTION_TIMEOUT,
			]
		);
		$result   = wp_remote_retrieve_body( $response );

		$result = json_decode( $result );

		if ( ! isset( $result ) ) {
			throw new Exception( 'Something went wrong. Please try again later.' );
		}

		if ( $result->success ) {
			return $result->data->historyData;
		} else {
			throw new Exception( $result->message->text );
		}
	}

	public function get_mobikwik_connection_data() {
		$data = [
			'mode'                => 'live',
			'gateway'             => 'mobikwik',
			'source'              => 'config',
			'amount'              => '0',
			'currency'            => 'INR',
			'knitpay_version'     => KNITPAY_VERSION,
			'knitpay_upi_version' => KNITPAY_UPI_VERSION,
			'php_version'         => PHP_VERSION,
			'website_url'         => home_url( '/' ),
			'data'                => [
				'transaction_id' => '',
			],
		];

		\KnitPayPro::check_knit_pay_pro_setup();

		$response = Http::post(
			\KNIT_PAY_UPI_RAPIDAPI_BASE_URL . 'payments/upi/request',
			[
				'body'    => wp_json_encode( $data ),
				'headers' => [
					'X-RapidAPI-Host' => \KNIT_PAY_UPI_RAPIDAPI_HOST,
					'X-RapidAPI-Key'  => get_option( 'knit_pay_pro_setup_rapidapi_key' ),
				],
				'timeout' => self::CONNECTION_TIMEOUT,
			]
		);

		$result = $response->json();

		if ( '403' === (string) $response->status() ) {
			$api_link = ' https://rapidapi.com/knitpay/api/knit-pay-upi/pricing';
			throw new Exception( 'RapidAPI Error: ' . $result->message . $api_link );
		} elseif ( '200' !== (string) $response->status() ) {
			throw new Exception( 'RapidAPI Error: ' . $result->message );
		}

		return $result->data->mobikwik_data;
	}
}
