<?php
/**
 * PS_Label_Crypto — 100% VPS-backed crypto config + rate provider.
 *
 * Replaces PARCSELECT_API dependency in FREE plugin. All data (enabled coins,
 * wallet addresses, PLN->crypto conversion) comes from our VPS integrator:
 *   GET /labels/config
 *   GET /labels/rate?crypto=sol&pln=13.99
 *
 * Client plugin holds NO crypto secrets, wallets, or rates — single source
 * of truth is the VPS.
 *
 * @package ParcelSelector
 */

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

class Parcselect_Label_Crypto {

	const CONFIG_TTL = 5 * MINUTE_IN_SECONDS;
	const RATE_TTL   = 5 * MINUTE_IN_SECONDS;

	/**
	 * Build authed VPS request.
	 *
	 * @param string $endpoint path starting with /.
	 * @param array  $query    optional query params.
	 * @return array|false decoded JSON on success, false otherwise.
	 */
	private static function vps_get( $endpoint, $query = array() ) {
		$installation = get_option( 'parcselect_installation_id', '' );
		$secret       = get_option( 'parcselect_label_proxy_secret', '' );
		$base         = trim( (string) get_option( 'parcselect_label_proxy_url', 'https://parcelselector.com' ) );
		if ( empty( $installation ) || empty( $secret ) || empty( $base ) ) {
			return false;
		}
		$signature = hash_hmac( 'sha256', $installation, $secret );
		$url       = rtrim( $base, '/' ) . $endpoint;
		if ( ! empty( $query ) ) {
			$url .= ( false === strpos( $url, '?' ) ? '?' : '&' ) . http_build_query( $query );
		}
		$response = wp_remote_get(
			$url,
			array(
				'timeout' => 10,
				'headers' => array(
					'X-PS-Installation' => $installation,
					'X-PS-Secret'       => $signature,
					'X-PS-Timestamp'    => (string) time(),
					'Accept'            => 'application/json',
				),
			)
		);
		if ( is_wp_error( $response ) ) {
			return false;
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== (int) $code ) {
			return false;
		}
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		return is_array( $body ) ? $body : false;
	}

	/**
	 * Enabled coins with wallet addresses from VPS.
	 *
	 * @return array symbol => ['label', 'color', 'address']
	 */
	public static function get_enabled_coins() {
		$cached = get_transient( 'parcselect_label_vps_config' );
		if ( is_array( $cached ) ) {
			return $cached;
		}
		$data = self::vps_get( '/labels/config' );
		if ( ! $data || ! isset( $data['coins'] ) || ! is_array( $data['coins'] ) ) {
			return array();
		}
		$out = array();
		foreach ( $data['coins'] as $sym => $info ) {
			$sym = strtolower( sanitize_key( $sym ) );
			if ( empty( $info['address'] ) ) {
				continue;
			}
			$out[ $sym ] = array(
				'label'   => isset( $info['label'] ) ? $info['label'] : strtoupper( $sym ),
				'color'   => isset( $info['color'] ) ? $info['color'] : '#64748b',
				'address' => $info['address'],
			);
		}
		set_transient( 'parcselect_label_vps_config', $out, self::CONFIG_TTL );
		return $out;
	}

	/**
	 * Wallet map.
	 *
	 * @return array symbol => wallet
	 */
	public static function get_enabled_wallets() {
		$out = array();
		foreach ( self::get_enabled_coins() as $sym => $info ) {
			$out[ $sym ] = $info['address'];
		}
		return $out;
	}

	/**
	 * Convert PLN to crypto via VPS /labels/rate.
	 *
	 * Output matches Parcselect_API::convert_detailed() signature exactly so existing
	 * callers in class-ps-label-ajax.php work unchanged.
	 *
	 * @param float  $price_pln PLN amount.
	 * @param string $coin      Coin symbol (lowercase).
	 * @param string $fiat      Fiat code (ignored — VPS is PLN-native).
	 * @return array|false {amount, rate, sources, source_names}
	 */
	public static function convert_detailed( $price_pln, $coin, $fiat = 'pln' ) {
		$coin      = strtolower( (string) $coin );
		$price_pln = (float) $price_pln;
		if ( $price_pln <= 0 ) {
			return false;
		}
		$cache_key = 'parcselect_label_vps_rate_' . $coin;
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) && isset( $cached['rate'] ) ) {
			$rate = (float) $cached['rate'];
			return array(
				'amount'       => round( $price_pln / $rate, 6 ),
				'rate'         => $rate,
				'sources'      => (int) $cached['sources'],
				'source_names' => (string) $cached['source_names'],
			);
		}
		$data = self::vps_get( '/labels/rate', array( 'crypto' => $coin, 'pln' => $price_pln ) );
		if ( ! $data || empty( $data['rate'] ) ) {
			return false;
		}
		$rate = (float) $data['rate'];
		set_transient(
			$cache_key,
			array(
				'rate'         => $rate,
				'sources'      => isset( $data['sources'] ) ? (int) $data['sources'] : 1,
				'source_names' => isset( $data['source_names'] ) ? (string) $data['source_names'] : 'VPS',
			),
			self::RATE_TTL
		);
		return array(
			'amount'       => isset( $data['amount'] ) ? (float) $data['amount'] : round( $price_pln / $rate, 6 ),
			'rate'         => $rate,
			'sources'      => isset( $data['sources'] ) ? (int) $data['sources'] : 1,
			'source_names' => isset( $data['source_names'] ) ? (string) $data['source_names'] : 'VPS',
		);
	}
}
