<?php
/**
 * File that define P24_Order_Generator_Support class.
 *
 * @package Przelewy24
 */

defined( 'ABSPATH' ) || exit;

use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;

/**
 * Additional methods to help generate different payloads for different API.
 */
class P24_Order_Generator_Support {

	/**
	 * Get a number for the provided order.
	 *
	 * @param WC_Order $order The provided order.
	 * @return string
	 */
	public static function get_number( WC_Order $order ) {
		$description_order_id = $order->get_order_number();
		/* Support for the Sequential Order Numbers Pro plugin. */
		if ( class_exists( 'WC_Seq_Order_Number_Pro' ) ) {
			$seq                  = new WC_Seq_Order_Number_Pro();
			$description_order_id = $seq->get_order_number( $description_order_id, $order );
		} elseif ( class_exists( 'WC_Seq_Order_Number' ) ) {
			$seq                  = new WC_Seq_Order_Number();
			$description_order_id = $seq->get_order_number( $description_order_id, $order );
		}
		return (string) $description_order_id;
	}

	/**
	 * Get a description for the provided order.
	 *
	 * @param bool     $test_mode True for sandbox.
	 * @param WC_Order $order The provided order.
	 * @return string
	 */
	public static function get_description( $test_mode, WC_Order $order ) {
		$prefix = $test_mode ? __( 'Transakcja testowa', 'przelewy24' ) . ', ' : '';
		$suffix = __( 'Zamówienie nr', 'przelewy24' ) . ': ' . self::get_number( $order ) . ', ' . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() . ', ' . gmdate( 'Ymdhi' );

		return $prefix . $suffix;
	}

	/**
	 * Extract language from locale.
	 *
	 * @param string $locale Provided locale.
	 * @return string
	 */
	public static function extract_language_from_locale( $locale ) {
		$rx = '/^[^_]+/';
		if ( preg_match( $rx, $locale, $m ) ) {
			return strtolower( $m[0] );
		} else {
			return 'pl';
		}
	}

	/**
	 * Generate session/transaction for an order.
	 *
	 * @param WC_Order $order The order that need a session.
	 * @return string
	 */
	public static function generate_transaction( WC_Order $order ) {
		$order_id = (int) $order->get_id();
		return $order_id . '_' . uniqid( md5( wp_rand() ), true );
	}
}
