<?php

namespace KnitPayUPI\Gateways\UpiQR\GpayBiz;

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

/**
 * Title: Google Pay Business Integration
 * Copyright: 2020-2026 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.8.0.0
 * @since   1.8.0.0
 */
class Integration extends KnitPayUPIIntegration {
	/**
	 * Construct Google Pay Business integration.
	 *
	 * @param array $args Arguments.
	 */
	public function __construct( $args = [] ) {
		$args = wp_parse_args(
			$args,
			[
				'id'                 => 'gpay-biz',
				'name'               => 'UPI/QR - GPay Business (Beta)',
				'product_url'        => 'https://pay.google.com/g4b',
				'provider'           => 'gpay-biz',
				'gateway_name'       => 'Google Pay for Business',
				'terms_url'          => 'https://policies.google.com/terms',
				'short_id'           => 'gpaybiz',
				'refresh_connection' => true,
			]
		);

		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->merchant_id     = $this->get_meta( $post_id, 'upi_qr_gpay_biz_merchant_id' );
		$config->cookies         = $this->get_meta( $post_id, 'upi_qr_gpay_biz_cookies' );
		$config->connection_data = $this->get_meta( $post_id, 'upi_qr_gpay_biz_connection_data' );
		$config->wiz_global_data = $this->get_meta( $post_id, 'upi_qr_gpay_biz_wiz_global_data' );

		$config->hide_mobile_qr  = false;
		$config->hide_pay_button = true;

		return $config;
	}

	public function get_setup_settings_fields( $fields ) {
		if ( ! defined( 'KNIT_PAY_UPI_GPAY_BIZ' ) ) {
			unset( $fields[2] );

			// Steps to Integrate.
			$fields[1] = [
				'section'  => 'general',
				'type'     => 'custom',
				'callback' => function () {
					echo '
					<h1>Steps to Integrate Google Pay Business</h1>
					<ol>
						<li>Ultra or Mega plan is required for atleast one month to use Google Pay Business.</li>
						<br><li><a target="_blank" href="https://www.knitpay.org/contact-us/">Contact us</a> for the integration assistance.</li>
					</ol>';
				},
			];

			return $fields;
		}

		$fields = $this->get_login_logout_fields( $fields );
		
		// WP Cron URL.
		/*
		$fields[] = [
			'section'  => 'general',
			'title'    => \__( 'WP Cron URL', 'knit-pay-upi' ),
			'type'     => 'text',
			'classes'  => [ 'large-text', 'code' ],
			'value'    => site_url( 'wp-cron.php' ),
			'readonly' => true,
			'callback' => function () {
				echo 'We recommend setting up WP-Cron to run at least twice per hour (every 30 minutes) to help prevent session timeouts. For reliable scheduling, configure your system task scheduler to call your site\'s <code>wp-cron.php</code>. See the documentation for details.<br>' .
				'<a target="_blank" rel="noopener noreferrer" href="https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/">https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/</a>';
			},
		];*/

		unset( $fields['transaction_id_field'] );

		return $fields;
	}

	private function get_login_logout_fields( $fields ) {
		// Connection Status.
		$config_id = KnitPayUtils::get_gateway_config_id();
		if ( ! empty( $config_id ) ) {
			$config = $this->get_config( $config_id );
		}

		// Already connected, check status.
		if ( isset( $config ) && is_array( $config->cookies ) && ! empty( $config->merchant_id ) ) {
			try {
				$api_client = new Client( $config );
				$api_client->check_connection();

				$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>';
					},
				];
				
				$message  = '<strong>Knit Pay</strong> - The connection to GPay could not be established. Please ensure that the provided merchant ID and cookies are accurate.';
				$message .= ' ' . $e->getMessage();

				wp_admin_notice( $message, [ 'type' => 'error' ] );
				return $fields;
			}
			
			$fields = parent::get_setup_settings_fields( $fields );

			return $fields;
		}

		// Merchant ID.
		$fields[] = [
			'section'  => 'general',
			'meta_key' => '_pronamic_gateway_upi_qr_gpay_biz_merchant_id',
			'title'    => __( 'Merchant ID', 'knit-pay-upi' ),
			'type'     => 'text',
			'classes'  => [ 'regular-text', 'code' ],
			'required' => true,
		];

		$fields[] = [
			'section'  => 'general',
			'meta_key' => '_pronamic_gateway_upi_qr_gpay_biz_cookies',
			'title'    => __( 'Cookies', 'knit-pay-upi' ),
			'type'     => 'textarea',
			'classes'  => [ 'regular-text', 'code' ],
			'required' => true,
		];
		
		return $fields;
	}
	
	/**
	 * Save post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public function save_post( $config_id ) {
		if ( ! defined( 'KNIT_PAY_UPI_GPAY_BIZ' ) ) {
			$this->knit_pay_post_save_notice( 'Google Pay Business is not connected. Contact us for the integration assistance.' );
			return;
		}

		$config = $this->get_config( $config_id );

		if ( '' !== $config->connection_data ) {
			return;
		}

		if ( ! is_array( $config->cookies ) ) {
			$cookies = KnitPayUtils::convert_cookie_string_to_wp_cookies( $config->cookies, 'google.com' );

			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_gpay_biz_cookies', $cookies );
		}

		try {
			$this->get_gpay_biz_connection_data( $config_id );
		} catch ( Exception $e ) {
			$this->knit_pay_post_save_notice( $e->getMessage() );
			return;
		}
	}

	// Get Business Name and VPA.
	private function save_merchant_details( $config_id ) {
		$config = $this->get_config( $config_id );

		try {
			$api           = new Client( $config );
			$merchant_info = $api->get_merchant_details();
		} catch ( Exception $e ) {
			$this->knit_pay_post_save_notice( $e->getMessage() );
			return;
		}
		
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_vpa', $merchant_info['vpa'] );
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_payee_name', $merchant_info['payee_name'] );
	}

	private function get_gpay_biz_connection_data( $config_id ) {
		$config = $this->get_config( $config_id );

		try {
			$api_client               = new Client( $config );
			$gpay_biz_connection_data = $api_client->get_gpay_biz_connection_data();
		} catch ( Exception $e ) {
			$this->knit_pay_post_save_notice( $e->getMessage() );
			return;
		}

		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_gpay_biz_connection_data', wp_slash( $gpay_biz_connection_data ) );

		if ( ! as_has_scheduled_action( 'knit_pay_upi_gpaybiz_refresh_connection', [ 'config_id' => $config_id ], 'knit-pay-upi' ) ) {
			\as_schedule_recurring_action(
				time(),
				300,
				'knit_pay_upi_gpaybiz_refresh_connection',
				[ 'config_id' => $config_id ],
				'knit-pay-upi'
			);
		}
	}
	
	public function refresh_connection( $config_id ) {
		try {
			$config     = $this->get_config( $config_id );
			$api_client = new Client( $config );
			$api_client->check_connection();
		} catch ( Exception $e ) {
			// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			// Don't show error, because this might be temporary issue and it might not cause any later issue.
		}
	}

	public static function clear_config( $config_id ) {
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_gpay_biz_connection_data' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_gpay_biz_cookies' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_gpay_biz_wiz_global_data' );

		delete_transient( 'knit_pay_upi_gpay_get_wiz_data_' . $config_id );
		delete_transient( 'knit_pay_upi_gpay_rotate_cookies_' . $config_id );
		
		as_unschedule_all_actions( 'knit_pay_upi_gpaybiz_refresh_connection', [ 'config_id' => $config_id ], 'knit-pay-upi' );
	}
}
