<?php

if (!defined('ABSPATH')) {
	exit;
}

class WC_Verifone_Onboarding {
	/**
	 * Check if onboarding should be shown.
	 *
	 * @return boolean
	 */
	public static function should_onboard() {
		// Check if onboarding already completed
		$tcsonboarding_completed = get_option( 'woocommerce_verifone_onboarding_completed' );
		if ( $tcsonboarding_completed ) {
			return false;
		}

		// Check if there's already orders with gateway, as that's indication that it has been set up at least once
		$orders = wc_get_orders( [
			'limit'          => 1,
			'return'         => 'ids',
			'payment_method' => WC_VERIFONE_GATEWAY_ID,
		] );

		if ( ! empty( $orders ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Get merchant agreement code from settings or POST data.
	 *
	 * Reading from POST is needed to get the value before settings are saved, as this is called during admin_options rendering where settings might not yet be saved.
	 * Value is used as placeholder in the input field and not stored by this function.
	 *
	 * @return string|null Merchant agreement code or null if not set
	 */
	public static function get_merchant_agreement() {
		$config = WC_Verifone_Config::getInstance();
		$code = $config->getMerchantAgreement();
		return $code;
	}

	/**
	 * Check if merchant agreement code is set.
	 *
	 * @return boolean
	 */
	public static function is_merchant_set() {
		$code = self::get_merchant_agreement();
		return ! empty( $code );
	}

	/**
	 * Get TCS portal url with needed parameters for onboarding on that side.
	 *
	 * @return string TCS portal url
	 */
	public static function get_tcs_url() {
		$config = WC_Verifone_Config::getInstance();

		$base = WC_Verifone_Urls::TCS_PORTAL_BASE . '/wooCommerceMerchantSettingsController.html';
		if ( ! $config->isLiveMode() ) {
			$base = WC_Verifone_Urls::TCS_PORTAL_BASE_DEMO . '/wooCommerceMerchantSettingsController.html';
		}

		$shop_public_key_encoded = '';
		if ( $config->getShopPublicKey() ) {
			$shop_public_key_encoded = base64_encode( $config->getShopPublicKey() );
		}

		$args = [
			'shop_public_key' => $shop_public_key_encoded,
			'shop_merchant_agreement_code' => self::get_merchant_agreement() ?? '',
			'shop_delayed_success_url' => urlencode( WC_Verifone_Urls::getPaymentDelayedLink() ),
			'return_url' => urlencode( add_query_arg( 'tcsonboarding', 'done', WC_Verifone_Urls::getSettingsUrl() ) ),
		];

		return add_query_arg( $args, $base );
	}

	/**
	 * Render the onboarding HTML if needed.
	 *
	 * @return void
	 */
	public static function render() {
		if ( ! self::should_onboard() ) {
			return;
		}

		$active_step = 'merchant';
		if ( self::is_merchant_set() ) {
			$active_step = 'tcs';
		}

		if ( isset( $_GET['tcsonboarding'] ) && 'done' === $_GET['tcsonboarding'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended - no need to verify, its just a basic check without logic using the value or performing actions that could be harmful
			// Get the payment methods for the first time
			try {
                $methods_response = WC_Verifone_Core_PaymentMethods::refreshAvailablePaymentMethods();
                if ( is_array( $methods_response ) ) {
                    $methods_refreshed = true;
                }
            } catch (Exception $e) {
                $exceptionMessage = $e->getMessage();
            }

			update_option( 'woocommerce_verifone_onboarding_completed', wp_date( 'Y-m-d H:i:s' ) );
		}

		$tcsonboarding_completed = get_option( 'woocommerce_verifone_onboarding_completed' );
		if ( $tcsonboarding_completed ) {
			$active_step = 'done';
		}

		WC_Verifone_Tpl::render( [
			'merchant_code' => self::get_merchant_agreement() ?? 'ECxxxxx',
			'active_step'	=> $active_step,
			'tcs_url'		=> self::get_tcs_url(),
		], 'onboarding.thtml' );
	}
}
