<?php
/**
 * Custom Thank You page script for ADA Payments
 * This handles wallet connection on the order-received page
 */

/**
 * Deprecated template_redirect hook – replaced by woocommerce_thankyou for reliable order detection.
 */
/**
 * Inject ADA wallet UI on the thank‑you page via WooCommerce's `woocommerce_thankyou` hook.
 */
add_action('woocommerce_thankyou', function( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order || $order->get_payment_method() !== 'ada_payment' ) {
        return;
    }

    $settings = get_option( 'woocommerce_ada_payment_settings' );
    $store_currency = $order->get_currency();
    $order_total = (float) $order->get_total();

    // Get ADA price in the store currency via CoinAPI
    $ada_price_in_currency = ADAPAYFWC_get_ada_price_in_currency( $store_currency, $settings );
    $ada_amount = $ada_price_in_currency > 0 ? $order_total / $ada_price_in_currency : 0;

    $data = array(
        'orderId'           => $order_id,
        'adaLovelace'       => (int) round( $ada_amount * 1000000 ),
        'adaAmount'         => number_format( $ada_amount, 2 ),
        'storeAddress'      => $settings['walletAddress'] ?? '',
        'networkId'         => str_contains( $settings['network'] ?? '', 'preview' ) ? 0 : 1,
        'apiEndpoint'       => home_url( '/wp-json/adapayments-woocommerce/v1' ),
        'nonce'             => wp_create_nonce( 'wp_rest' ),
        'is_checkout_blocks'=> false,
    );

    wp_add_inline_script( 'jquery', 'window.ADAPAYMENT_CheckoutData = ' . wp_json_encode( $data ) . ';', 'before' );
}, 20 );

function ADAPAYFWC_get_ada_price_in_currency( $currency, $settings ) {
    $currency = strtoupper( $currency );
    $cache_key = 'ada_price_' . strtolower( $currency );
    $cached = get_transient( $cache_key );
    if ( $cached !== false ) return (float) $cached;

    $api_key = ! empty( $settings['coinMarketCapKey'] ) ? $settings['coinMarketCapKey'] : null;

    if ( $api_key ) {
        $resp = wp_remote_get( 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=ADA&convert=' . $currency, array(
            'timeout' => 10,
            'headers' => array( 'X-CMC_PRO_API_KEY' => $api_key ),
        ) );

        if ( ! is_wp_error( $resp ) ) {
            $body = json_decode( wp_remote_retrieve_body( $resp ), true );
            $price = $body['data']['ADA']['quote'][ $currency ]['price'] ?? 0;
            if ( $price > 0 ) {
                set_transient( $cache_key, $price, HOUR_IN_SECONDS );
                return (float) $price;
            }
        }
    }

    // Fallback: CoinGecko free public API (no key required)
    $resp = wp_remote_get( 'https://api.coingecko.com/api/v3/simple/price?ids=cardano&vs_currencies=' . strtolower( $currency ), array(
        'timeout' => 10,
    ) );

    if ( ! is_wp_error( $resp ) ) {
        $body = json_decode( wp_remote_retrieve_body( $resp ), true );
        $price = $body['cardano'][strtolower( $currency )] ?? 0;
        if ( $price > 0 ) {
            set_transient( $cache_key, $price, HOUR_IN_SECONDS );
            return (float) $price;
        }
    }

    return 0;
} 
