<?php

namespace SugarCalendarBookings\Payments\Gateways\Stripe;

use SugarCalendarBookings\Vendor\Stripe\StripeClient;
use SugarCalendarBookings\Payments\PaymentsHelpers;
use SugarCalendarBookings\Plugin;

/**
 * Class StripeHelpers.
 *
 * @since 1.0.0
 */
class StripeHelpers {

	/**
	 * Get API client.
	 *
	 * @since 1.0.0
	 *
	 * @return StripeClient
	 */
	public static function get_client() {

		static $client;

		if ( is_null( $client ) ) {
			$credentials = Plugin::get( StripePaymentGateway::class )->get_credentials();

			$client = new StripeClient(
				[
					'api_key' => $credentials['secret_key'],
				]
			);
		}

		return $client;
	}

	/**
	 * Get zero-decimal currencies.
	 *
	 * @since 1.0.0
	 *
	 * @return string[]
	 */
	private static function get_zero_decimal_currencies() {

		return [
			'BIF',
			'CLP',
			'DJF',
			'GNF',
			'JPY',
			'KMF',
			'KRW',
			'MGA',
			'PYG',
			'RWF',
			'VND',
			'VUV',
			'XAF',
			'XOF',
			'XPF',
		];
	}

	/**
	 * Get amount depending on currency.
	 *
	 * @since 1.0.0
	 *
	 * @param float  $price    Price.
	 * @param string $currency Currency.
	 *
	 * @return int
	 */
	public static function get_amount( $price, $currency = null ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded

		if ( $currency === null ) {
			$currency = PaymentsHelpers::get_currency();
		}

		$price = floatval( $price );

		if ( ! in_array( $currency, self::get_zero_decimal_currencies(), true ) ) {
			$price *= 100;
		}

		return intval( round( $price ) );
	}

	/**
	 * Sanitize and truncate a string to Stripe's metadata value limit.
	 *
	 * Stripe enforces a 500-character limit on metadata values; longer
	 * values are rejected at API time. Tags are stripped as a defense-in-depth
	 * measure since metadata is visible in the Stripe Dashboard.
	 *
	 * @since 1.5.0
	 *
	 * @param string $value Raw value.
	 *
	 * @return string Sanitized, truncated value.
	 */
	public static function truncate_metadata_value( string $value ): string {

		$value = trim( wp_strip_all_tags( $value ) );

		return mb_substr( $value, 0, 500 );
	}
}
