<?php
/**
 * Lite-mode BTC transaction checker (polls blockchain.info).
 *
 * Reads the expected wallet/amount from order meta, scans unspent outputs
 * for a match, and updates order status accordingly. Updates `cryptoniq_is_paid`
 * or `cryptoniq_is_failed` so the AJAX checker can return a clean response
 * to the front-end (same shape as PRO/webhook mode).
 */

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

function cryptoniq_coin_check_btc( $order ) {
    if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
        return;
    }

    $status = $order->get_status();
    if ( in_array( $status, array( 'failed', 'cancelled' ), true ) ) {
        return;
    }

    $wallet = $order->get_meta( 'cryptoniq_coin_wallet' );
    $amount = $order->get_meta( 'cryptoniq_coin_amount' );
    $id     = $order->get_id();

    if ( ! $wallet || ! $amount ) {
        return;
    }

    // Window: 3h from order start, matching the lite checkout copy.
    $time_start   = (int) $order->get_meta( 'cryptoniq_time_start' );
    $time_counter = 60 * 60 * 3;
    $time_end     = $time_start + $time_counter;
    $time_current = time();

    $request = cryptoniq_remote_get( 'BTC', $wallet );

    if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) !== 200 ) {
        // Couldn't reach the explorer — just give up this round, retry on
        // the next AJAX poll. Don't fail the order on a network blip.
        return;
    }

    $content = json_decode( wp_remote_retrieve_body( $request ), true );
    $txs     = isset( $content['unspent_outputs'] ) ? $content['unspent_outputs'] : array();

    // Normalize the expected amount for exact-match comparison.
    $expected = number_format( (float) str_replace( ',', '', (string) $amount ), 8, '.', '' );

    if ( is_array( $txs ) ) {
        foreach ( $txs as $tx ) {
            $tx_amount = number_format( (float) $tx['value'] / 100000000, 8, '.', '' );
            if ( (float) $tx_amount !== (float) $expected ) {
                continue;
            }

            $txid = isset( $tx['tx_hash'] ) ? $tx['tx_hash'] : '';

            // Same txid already used by another order? Skip it.
            if ( $txid && cryptoniq_check_txid( $txid, $id ) === 1 ) {
                continue;
            }

            // Within the window → mark paid.
            if ( $time_current <= $time_end ) {
                $confirmations = isset( $tx['confirmations'] ) ? (int) $tx['confirmations'] : 0;

                if ( $confirmations >= 0 && $txid ) {
                    cryptoniq_tx_data_update( $txid, $id );
                }
                if ( $confirmations >= 1 ) {
                    $order_status = cryptoniq_get_option( 'order_status' ) ?: 'processing';
                    Cryptoniq_AJAX::order_status_update( $id, $txid, $order_status );
                }
                return;
            }
        }
    }

    // No match and window expired → fail the order.
    if ( $time_current > $time_end ) {
        Cryptoniq_AJAX::order_status_update( $id, '', 'failed' );
    }
}
