<?php

namespace KnitPayUPI\Gateways\UpiQR\TataNeu;

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

/**
 * Prevent loading this file directly
 */
defined( 'ABSPATH' ) || exit();

/**
 * Title: Tata Neu for Business API Client
 * Copyright: 2020-2025 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.9.0.0
 * @since   1.9.0.0
 */
class Client {
	const CONNECTION_TIMEOUT = 5;

	private $config;

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

	public function get_upi_details() {
		$path = '/v3.1/vault/details';

		return $this->create_connection( $path, 'GET' )->paymentCards->upiDetails;
	}

	public function check_connection() {
		return $this->get_upi_details();
	}

	public function get_order_history( $tata_neu_data ) {
		$path = '/order/v2/customerHash/order-history';

		try {
			return $this->create_connection( $path, 'POST', $tata_neu_data );
		} catch ( Exception $e ) {
			return [];
		}
	}

	private function create_connection( $path, $method, $data = null, $save_cookies = true ) {
		if ( '' === $this->config->access_token ) {
			throw new Exception( 'Tata Neu is not connected.' );
		}

		$headers = [
			'Content-Type'    => 'application/json',
			'Accept'          => 'application/json, text/plain, */*',
			'Authorization'   => 'Bearer ' . $this->config->access_token,
			'client_id'       => 'TCP-WEB-APP',
			'accept-language' => 'en-US,en;q=0.9',
			'User-Agent'      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36',
		];

		$args = [
			'method'  => $method,
			'timeout' => self::CONNECTION_TIMEOUT,
			'headers' => $headers,
		];

		if ( 'POST' === $method ) {
			$args['body'] = $data;
		}

		$url      = 'https://api.tatadigital.com/api' . $path;
		$response = wp_remote_request( $url, $args );

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

			// If redirected to login page, throw error.
			throw new Exception( 'Tata Neu is not connected.', $status_code );
		}

		$response_body = wp_remote_retrieve_body( $response );

		$result = json_decode( $response_body );

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

		if ( isset( $result->statusInfo ) && 'Success' === $result->statusInfo->status ) {
			return $result->orders;
		} elseif ( isset( $result->paymentCards ) ) {
			return $result;
		} else {
			$error_message = '';
			if ( ! empty( $result->errorMessage ) ) {
				$error_message = $result->errorMessage;
			} elseif ( ! empty( $result->errorReason ) ) {
				$error_message = $result->errorReason;
			} elseif ( ! empty( $result->message ) ) {
				$error_message = $result->message;
			} elseif ( isset( $result->statusInfo ) && isset( $result->statusInfo->errorInfo ) ) {
				$error_message = $result->statusInfo->errorInfo->errorMessage;
			} else {
				$error_message = 'Something went wrong. Please try again later.';
			}
			throw new Exception( $error_message );
		}
	}
}
