<?php
/**
 * Shared rate-related helper methods used by both block renderers.
 *
 * Centralises adjustment-percent sanitisation / formatting,
 * amount sanitisation, and cache-TTL derivation so neither
 * block class needs its own copy.
 *
 * @package CRTodayCurrencyBlocks
 */

declare(strict_types=1);

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

trait CRToday_Rate_Helpers {

	/**
	 * Clamp an adjustment percentage to [−100, +100], returning 0 for non-numeric input.
	 *
	 * @param mixed $raw Raw value from attributes / shortcode.
	 */
	private static function sanitize_adjustment_percent($raw): float {
		if (! is_numeric($raw)) {
			return 0.0;
		}

		$percent = (float) $raw;
		if (! is_finite($percent)) {
			return 0.0;
		}

		return max(-100.0, min(100.0, $percent));
	}

	/**
	 * Whether an adjustment percentage is effectively non-zero.
	 */
	private static function has_adjustment(float $percent): bool {
		return abs($percent) > 0.0000001;
	}

	/**
	 * Format an adjustment percentage for display (e.g. "+2.5", "−0.3").
	 */
	private static function format_adjustment_percent(float $percent): string {
		$formatted = rtrim(rtrim(sprintf('%.2F', abs($percent)), '0'), '.');
		if ($formatted === '') {
			$formatted = '0';
		}

		return ($percent > 0 ? '+' : ($percent < 0 ? '-' : '')) . $formatted;
	}

	/**
	 * Derive cache TTL in seconds from the admin API-interval setting.
	 *
	 * Delegates to the canonical implementation in CRToday_Plugin_Settings.
	 */
	private static function cache_ttl(): int {
		$config = CRToday_Plugin_Settings::get_config();
		return max(1, (int) $config['api_interval']) * 60;
	}

	/**
	 * Parse an ISO-8601 / RFC-style timestamp string into a Unix timestamp.
	 *
	 * @param string $timestamp  Raw timestamp string from API or view model.
	 * @param int    $fallback   Value to return on parse failure (default 0).
	 *
	 * @return int Unix timestamp or $fallback.
	 */
	private static function parse_iso_timestamp(string $timestamp, int $fallback = 0): int {
		if ($timestamp === '') {
			return $fallback;
		}

		$parsed = strtotime($timestamp);
		if ($parsed === false || $parsed <= 0) {
			return $fallback;
		}

		return $parsed;
	}

	/**
	 * Determine the rendering state of a view model based on its rates array.
	 */
	private static function view_model_state(array $view_model): string {
		if (! isset($view_model['rates']) || ! is_array($view_model['rates']) || $view_model['rates'] === []) {
			return 'empty';
		}
		return 'ready';
	}
}
