<?php
/**
 * Pricing logic — shipping provider price + margin, rounded to .99.
 *
 * @package ParcelSelector
 * @since   3.4.0
 */

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

class Parcselect_Label_Pricing {

	/**
	 * Calculate final price: shipping provider base + margin → rounded up to .99.
	 *
	 * Examples:
	 *   13.20 + 1.00 = 14.20 → 14.99
	 *   14.80 + 1.00 = 15.80 → 15.99
	 *   14.99 + 1.00 = 15.99 → 15.99
	 *
	 * @param float $shipping_provider_price Base price from label API.
	 * @return float Final price ending in .99.
	 */
	public static function calculate( $shipping_provider_price ) {
		$margin = (float) get_option( 'parcselect_label_margin', 1.00 );
		$raw    = $shipping_provider_price + $margin;
		$final  = floor( $raw ) + 0.99;

		// If rounding down put us below the raw price, go up one.
		if ( $final < $raw ) {
			$final += 1.00;
		}

		return round( $final, 2 );
	}

	/**
	 * Convert PLN amount to SOL. Delegates to the VPS-backed rate client.
	 *
	 * @param float  $amount   Fiat amount.
	 * @param string $currency Fiat currency code (default: order currency or PLN).
	 * @return array|false [ 'amount' => '0.0087', 'rate' => 1724.50, 'sources' => 1, 'source_names' => 'VPS' ] or false.
	 */
	public static function to_sol( $amount, $currency = '' ) {
		if ( empty( $currency ) ) {
			$currency = get_woocommerce_currency();
		}

		if ( ! class_exists( 'Parcselect_Label_Crypto' ) ) {
			return false;
		}

		return Parcselect_Label_Crypto::convert_detailed( $amount, 'sol', $currency );
	}

	/**
	 * Get Solana wallet address. Wallet lives on VPS only — this local option
	 * is just a display cache populated from the /labels/config response.
	 *
	 * @return string Wallet address or empty string.
	 */
	public static function get_sol_wallet() {
		return trim( (string) get_option( 'parcselect_label_wallet_sol', '' ) );
	}

	/**
	 * Format price for display (e.g. "14.99 PLN").
	 *
	 * @param float  $price    The price.
	 * @param string $currency Currency code.
	 * @return string Formatted price.
	 */
	public static function format( $price, $currency = '' ) {
		if ( empty( $currency ) ) {
			$currency = get_woocommerce_currency();
		}
		return number_format( $price, 2, '.', '' ) . ' ' . $currency;
	}
}
