<?php
defined( 'ABSPATH' ) || exit;

class ChainPay_Price_Feed {

    const TRANSIENT    = 'chainpay_prices';
    const TRANSIENT_TTL = 300; // 5 min

    public static function get_rate( $coin_key, $currency = null ) {
        if ( null === $currency ) {
            $currency = get_woocommerce_currency();
        }
        $prices = self::get_all( $currency );
        return isset( $prices[ $coin_key ] ) ? (float) $prices[ $coin_key ] : 0.0;
    }

    public static function get_all( $currency = null ) {
        if ( null === $currency ) $currency = get_woocommerce_currency();
        $key    = self::TRANSIENT . '_' . strtolower( $currency );
        $cached = get_transient( $key );
        if ( is_array( $cached ) && ! empty( $cached ) ) return $cached;
        return self::refresh_all( $currency );
    }

    public static function refresh_all( $currency = null ) {
        if ( null === $currency ) $currency = get_woocommerce_currency();
        $cur    = strtolower( $currency );
        $coins  = ChainPay_Coin_Registry::all();
        $ids    = array_unique( array_column( $coins, 'coingecko' ) );
        $id_str = implode( ',', $ids );
        $prices = array();

        // CoinGecko
        $cg_url  = 'https://api.coingecko.com/api/v3/simple/price?ids=' . $id_str . '&vs_currencies=' . $cur . ',usd';
        $cg_key  = (string) get_option( 'chainpay_coingecko_key', '' );
        if ( '' !== $cg_key ) $cg_url .= '&x_cg_api_key=' . $cg_key;

        $cg_resp = wp_remote_get( $cg_url, array( 'timeout' => 10 ) );
        if ( ! is_wp_error( $cg_resp ) ) {
            $data = json_decode( wp_remote_retrieve_body( $cg_resp ), true );
            if ( is_array( $data ) ) {
                foreach ( $coins as $key => $coin ) {
                    $cg_id = $coin['coingecko'];
                    if ( isset( $data[ $cg_id ][ $cur ] ) ) {
                        $prices[ $key ] = (float) $data[ $cg_id ][ $cur ];
                    } elseif ( isset( $data[ $cg_id ]['usd'] ) ) {
                        $prices[ $key ] = (float) $data[ $cg_id ]['usd'];
                    }
                }
            }
        }

        // Stablecoins
        foreach ( array( 'USDT_TRC20', 'USDT_ERC20', 'USDC' ) as $stable ) {
            $prices[ $stable ] = 1.0;
        }

        // Binance fallback for missing
        $binance = array(
            'BTC' => 'BTCUSDT', 'ETH' => 'ETHUSDT', 'LTC' => 'LTCUSDT',
            'BNB' => 'BNBUSDT', 'DOGE' => 'DOGEUSDT', 'SOL' => 'SOLUSDT',
            'MATIC' => 'MATICUSDT', 'TRX' => 'TRXUSDT', 'AVAX' => 'AVAXUSDT', 'ARB' => 'ARBUSDT',
        );
        foreach ( $binance as $coin_key => $symbol ) {
            if ( isset( $prices[ $coin_key ] ) && $prices[ $coin_key ] > 0 ) continue;
            $r = wp_remote_get( 'https://api.binance.com/api/v3/ticker/price?symbol=' . $symbol, array( 'timeout' => 5 ) );
            if ( ! is_wp_error( $r ) ) {
                $d = json_decode( wp_remote_retrieve_body( $r ), true );
                if ( isset( $d['price'] ) ) $prices[ $coin_key ] = (float) $d['price'];
            }
        }

        if ( ! empty( $prices ) ) {
            set_transient( self::TRANSIENT . '_' . $cur, $prices, self::TRANSIENT_TTL );
        }

        return $prices;
    }

    public static function fiat_to_crypto( $fiat, $coin_key, $decimals = 8, $currency = null ) {
        $rate = self::get_rate( $coin_key, $currency );
        if ( $rate <= 0.0 ) return '0';
        return number_format( (float) $fiat / $rate, $decimals, '.', '' );
    }

    public static function get_routed_coins() {
        $enabled = ChainPay_Coin_Registry::enabled();
        if ( 'yes' !== get_option( 'chainpay_smart_routing', 'yes' ) ) return $enabled;

        $eth_gas   = self::get_eth_gas_usd();
        $threshold = (float) get_option( 'chainpay_eth_fee_threshold', 30 );

        if ( $eth_gas <= $threshold ) return $enabled;

        $routed = array();
        foreach ( $enabled as $k => $c ) {
            $net = isset( $c['network'] ) ? $c['network'] : '';
            if ( false !== strpos( $net, 'Ethereum' ) || false !== strpos( $net, 'ERC' ) ) continue;
            $routed[ $k ] = $c;
        }
        return ! empty( $routed ) ? $routed : $enabled;
    }

    public static function get_eth_gas_usd() {
        $cached = get_transient( 'chainpay_eth_gas' );
        if ( false !== $cached ) return (float) $cached;
        $eth_usd = self::get_rate( 'ETH', 'USD' );
        $gas_usd = 25.0; // Default
        $r = wp_remote_get( 'https://api.ethgasstation.info/api/fee-estimate', array( 'timeout' => 5 ) );
        if ( ! is_wp_error( $r ) ) {
            $d = json_decode( wp_remote_retrieve_body( $r ), true );
            if ( isset( $d['gasPrice']['fast'] ) ) {
                $gas_usd = ( (float) $d['gasPrice']['fast'] * 21000 * 1e-9 ) * $eth_usd;
            }
        }
        set_transient( 'chainpay_eth_gas', $gas_usd, 120 );
        return $gas_usd;
    }
}
