<?php

namespace KnitPayUPI\Gateways\UpiQR\Mobikwik;

use KnitPayUPI\Gateways\UpiQR\KnitPayUPIIntegration;
use KnitPay\Utils;
use Exception;

/**
 * Title: MobiKwik Integration
 * Copyright: 2020-2026 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.6.0.0
 * @since   1.6.0.0
 */
class Integration extends KnitPayUPIIntegration {
	/**
	 * Construct MobiKwik integration.
	 *
	 * @param array $args Arguments.
	 */
	public function __construct( $args = [] ) {
		$args = wp_parse_args(
			$args,
			[
				'id'           => 'mobikwik',
				'name'         => 'UPI/QR - MobiKwik Personal',
				'product_url'  => 'http://go.thearrangers.xyz/mobikwik?utm_source=knit-pay&utm_medium=ecommerce-module&utm_campaign=module-admin&utm_content=product-url',
				'provider'     => 'mobikwik',
				'gateway_name' => 'MobiKwik',
			]
		);

		parent::__construct( $args );
	}
	
	/**
	 * Get config.
	 *
	 * @param int $post_id Config ID.
	 * @return Config
	 */
	public function get_config( $post_id ) {
		$config = new Config();
		$config->copy_properties( parent::get_config( $post_id ) );
		
		$config->token               = $this->get_meta( $post_id, 'upi_qr_mobikwik_token' );
		$config->payment_status_mode = $this->get_meta( $post_id, 'upi_qr_mobikwik_payment_status_mode' );
		
		$config->hide_mobile_qr       = false;
		$config->hide_pay_button      = true;
		$config->transaction_id_field = self::SHOW_REQUIRED_FIELD;

		return $config;
	}

	/**
	 * Get about settings fields.
	 *
	 * @return array
	 */
	public function get_about_settings_fields( $fields ) {
		$fields = parent::get_about_settings_fields( $fields );

		// Steps to Integrate.
		$fields[] = [
			'section'  => 'general',
			'type'     => 'custom',
			'title'    => 'Steps to Integrate MobiKwik',
			'callback' => function () {

				echo '<ol><li>Token can be found in the Local Storage, after login at <a target="_blank" href="https://www.mobikwik.com/login">https://www.mobikwik.com/login</a></li>
                    <ul>
                        <li><a target="_blank" href="https://firefox-source-docs.mozilla.org/devtools-user/storage_inspector/local_storage_session_storage/index.html">Firefox Local Storage</a></li>
                        <li><a target="_blank" href="https://developer.chrome.com/docs/devtools/storage/localstorage">Chrome Local Storage</a></li>
                    </ul>
                    <br><li>Feel free to <a target="_blank" href="https://www.knitpay.org/contact-us/">contact us</a> if you need help in generating retrieving Token</li>
                  </ol>';
			},
		];
		
		return $fields;
	}

	public function get_setup_settings_fields( $fields ) {
		// Token.
		// window.localStorage.getItem("_token")
		$fields[] = [
			'section'  => 'general',
			'meta_key' => '_pronamic_gateway_upi_qr_mobikwik_token',
			'title'    => __( 'Token', 'knit-pay-upi' ),
			'type'     => 'text',
			'classes'  => [ 'regular-text', 'code' ],
			'required' => true,
		];

		// Connection Status.
		$config_id = Utils::get_gateway_config_id();
		if ( ! empty( $config_id ) ) {
			$config = $this->get_config( $config_id );
		}
		if ( ! isset( $config ) || '' !== $config->token ) {
			try {
				$api_client      = new Client( $config );
				$connection_data = $this->get_meta( $config_id, 'upi_qr_mobikwik_connection_data' );
				$connection_data = json_decode( $connection_data, true );
				$api_client->get_wallet_history( $connection_data );

				$fields[] = [
					'section'  => 'general',
					'type'     => 'custom',
					'title'    => 'Connected',
					'callback' => function () {
						echo '<span class="dashicons dashicons-yes"></span>';
					},
				];
			} catch ( Exception $e ) {
				$fields[] = [
					'section'  => 'general',
					'type'     => 'custom',
					'title'    => 'Connected',
					'callback' => function () {
						echo '<span class="dashicons dashicons-no"></span>';
					},
				];
				
				self::clear_config( $config_id );
				
				$message = '<strong>Knit Pay</strong> - The connection to MobiKwik could not be established. Please ensure that the provided token is accurate.';
				wp_admin_notice( $message, [ 'type' => 'error' ] );
				return $fields;
			}

			$fields = parent::get_setup_settings_fields( $fields );
		}

		// Payment Status Mode.
		$fields[] = [
			'section'     => 'general',
			'meta_key'    => '_pronamic_gateway_upi_qr_mobikwik_payment_status_mode',
			'title'       => __( 'Payment Status Mode', 'knit-pay-upi' ),
			'type'        => 'select',
			'options'     => [
				'auto'         => 'Fully Automatic',
				'partial_auto' => 'Partially Automatic',
			],
			'default'     => 'auto',
			'description' => 'Fully Automatic - the payment status will be updated automatically. The amount collected might be slightly different than the actual. We will try to keep the collected amount as close to the actual amount as possible.<br>' .
			'Partially Automatic - the buyer will have to enter the UTR number to get the payment status.',
		];
		
		unset( $fields['transaction_id_field'] );
		unset( $fields['merchant_category_code'] );

		return $fields;
	}
	
	/**
	 * Save post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public function save_post( $config_id ) {       
		if ( '' !== $this->get_meta( $config_id, 'upi_qr_mobikwik_connection_data' ) ) {
			return;
		}
		
		$config        = $this->get_config( $config_id );
		$config->token = trim( $config->token, "'\"" );
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_mobikwik_token', $config->token );
		
		try {
			$api_client               = new Client( $config );
			$mobikwik_connection_data = $api_client->get_mobikwik_connection_data();
		} catch ( Exception $e ) {
			echo $e->getMessage();
			exit;
		}
		
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_mobikwik_connection_data', $mobikwik_connection_data );
	}
	
	private static function clear_config( $config_id ) {
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_mobikwik_connection_data' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_mobikwik_token' );
	}
}
