<?php

namespace KnitPayUPI\Gateways\UpiQR\Freecharge;

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

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

	private $config;

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

	public function get_endpoint() {
		return 'https://www.freechargebiz.in';
	}

	public function init_session() {
		$response = wp_remote_get(
			$this->get_endpoint() . '/api/ims/rest/create/csrf?showConsent=false&fcChannel=12',
			[
				'timeout' => self::CONNECTION_TIMEOUT,
			]
		);
		$result   = wp_remote_retrieve_body( $response );

		$result = json_decode( $result );

		if ( ! isset( $result->csrfRequestIdentifier ) ) {
			throw new Exception( 'Could not retrieve CSRF Identifier.' );
		}

		$freecharge_cookie = wp_remote_retrieve_cookie( $response, 'app_fc' );

		update_post_meta( $this->config->config_id, '_pronamic_gateway_upi_qr_freecharge_cookie', $freecharge_cookie );
		update_post_meta( $this->config->config_id, '_pronamic_gateway_upi_qr_freecharge_csrf_identifier', $result->csrfRequestIdentifier );

		return $this->config;
	}
	
	public function send_otp() {
		$path = '/api/ims/rest/otp/send/login/signup';
		$data = [
			'data' => [
				'request_type' => 'send_otp',
				'phone_number' => $this->config->phone_number,
			],
		];

		return $this->send_request( $path, $data );
	}

	public function verify_otp( $otp ) {
		$path = '/api/ims/rest/mobileOnly/verify';
		$data = [
			'data' => [
				'request_type' => 'verify_otp',
				'otp_id'       => $this->config->otp_id,
				'otp'          => $otp,
			],
		];

		return $this->send_request( $path, $data );
	}

	public function get_upi_status() {
		if ( '' === $this->config->cookie ) {
			throw new Exception( 'Freecharge is not connected.' );
		}

		$path = '/rest/upi/v2/upistatus';
		$data = [
			'device' => [
				'app' => '',
				'id'  => '',
			],
		];

		return $this->send_request( $path, $data, false );
	}

	public function check_connection() {
		if ( '' === $this->config->cookie ) {
			throw new Exception( 'Freecharge is not connected.' );
		}

		$data = [
			'paymentStatus'    => 0,
			'paymentDirection' => 0,
		];

		return $this->get_transaction_history( $data );
	}

	public function get_transaction_history( $data ) {
		if ( '' === $this->config->cookie ) {
			throw new Exception( 'Freecharge is not connected.' );
		}

		$path = '/thv/V2/listv3?fcAppType=MSITE';

		return $this->send_request( $path, $data, false );
	}

	private function send_request( $path, $data, $get_request_data = true ) {
		if ( $get_request_data ) {
			$data = $this->get_request_data_rapid( $data );
		}

		$response = wp_remote_post(
			$this->get_endpoint() . $path,
			[
				'body'    => wp_json_encode( $data ),
				'timeout' => self::CONNECTION_TIMEOUT,
				'cookies' => $this->get_cookies(),
				'headers' => $this->get_headers(),
			]
		);

		if ( 405 === wp_remote_retrieve_response_code( $response ) ) {
			Integration::clear_config( $this->config->config_id );

			throw new Exception( 'Freecharge is not connected.' );
		}

		$result = wp_remote_retrieve_body( $response );
		$result = json_decode( $result );

		$response_cookie = wp_remote_retrieve_cookie( $response, 'app_fc' );
		if ( ! empty( $response_cookie->value ) && $response_cookie->value !== $this->config->cookie->value ) {
			$this->config->cookie = $response_cookie;
			update_post_meta( $this->config->config_id, '_pronamic_gateway_upi_qr_freecharge_cookie', $response_cookie );
		}

		if ( ! ( isset( $result ) ) ) {
			throw new Exception( 'Something went wrong. Please try again later.' );
		} elseif ( isset( $result->data ) ) {
			return $result->data;
		} elseif ( isset( $result->error ) ) {
			throw new Exception( $result->error->errorMessage );
		}

		return (object) [];
	}

	public function get_request_data_rapid( $data = [], $return_charge_id = false ) {
		$data = wp_parse_args(
			$data,
			[
				'gateway'             => 'freecharge',
				'knitpay_version'     => KNITPAY_VERSION,
				'knitpay_upi_version' => KNITPAY_UPI_VERSION,
				'php_version'         => PHP_VERSION,
				'website_url'         => home_url( '/' ),
				'source'              => 'config',
				'amount'              => '0',
				'currency'            => 'INR',
				'mode'                => 'live',
				'data'                => [],
			]
		);
		
		\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 $return_charge_id ? $result : $result->data->freecharge_data;
	}

	private function get_headers() {
		return [
			'accept-language'       => 'en-US,en;q=0.9',
			'csrfRequestIdentifier' => $this->config->csrf_identifier,
			'fcChannel'             => '12',
			'Content-Type'          => 'application/json',
			'accept'                => 'application/json, text/plain, */*',
		];
	}

	private function get_cookies() {
		return [ $this->config->cookie ];
	}
}
