<?php

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


// Add Webhook Route
// ======================================================

function cryptoniq_webhook_callback( WP_REST_Request $request ) {
	$data        = $request->get_json_params();
	$license_key = cryptoniq_get_option( 'license_key' );

	// Reject requests when no license is set — without one the API server
	// shouldn't be pushing webhooks to this site in the first place.
	if ( empty( $license_key ) || ! isset( $data['licenseKey'] ) ) {
		return new WP_REST_Response( [ 'status' => 'unauthorized' ], 403 );
	}
	// Timing-safe comparison — prevents timing-attack-based license enumeration.
	if ( ! hash_equals( (string) $license_key, (string) $data['licenseKey'] ) ) {
		return new WP_REST_Response( [ 'status' => 'unauthorized' ], 403 );
	}

	if ( ! isset( $data['type'] ) || floatval( $data['amount'] ) <= 0 ) {
		return new WP_REST_Response( [ 'status' => 'ignored' ], 200 );
	}

	try {		
		cryptoniq_process_order( $data );
		
		return new WP_REST_Response( [ 'status' => 'ok' ], 200 );
	} catch ( Exception $e ) {		
		return new WP_REST_Response( [ 'status' => 'failed' ], 200 );
	}
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'cryptoniq/v1', '/webhook-callback', [
        'methods'             => 'POST',
        'callback'            => 'cryptoniq_webhook_callback',
        'permission_callback' => '__return_true',
    ] );
} );


// Process The Order
// ======================================================

function cryptoniq_process_order($data) {
	$order_status = cryptoniq_get_option('order_status');
	$asset = sanitize_text_field($data['asset']);
	$address = strtolower(sanitize_text_field($data['address']));
	$amount = floatval($data['amount']);
	$type = sanitize_text_field($data['type']);
	$timestamp = intval($data['timestamp']);
	$txid = sanitize_text_field($data['txId']);
	$time_counter = 3600;
	$process = false;
	$current_time = time();
	
	$args = array(
		'status' => array('wc-pending'),
		'limit'  => -1,
	);

	$orders = wc_get_orders( $args );

	$found = false;
	
	if (strlen($timestamp) === 13) {
		$timestamp = $timestamp / 1000;
	}
	
	if (!empty($orders)) {		
		foreach ($orders as $order) {
			$order_id = $order->get_id();
			$start_time = intval($order->get_meta('cryptoniq_time_start'));
			
			$payment_method = $order->get_payment_method();
			
			$time_start = intval($order->get_meta( 'cryptoniq_time_start' ));
			$time_end = $time_start + $time_counter;
			
			if ($start_time <= 0 || ($current_time - $start_time) > $time_counter) {
				continue;
			}

			if ($payment_method !== CRYPTONIQ_PAY_ID) {
				continue;
			}

			$coin_ticker = $order->get_meta( 'cryptoniq_coin_ticker' );
			
			$coin_amount = floatval($order->get_meta( 'cryptoniq_coin_amount' ));
			$coin_amount = number_format( (float) $coin_amount, cryptoniq_get_coin_data($coin_ticker, 'decimal'), '.', '' );
			$coin_wallet = strtolower($order->get_meta( 'cryptoniq_coin_wallet' ));
			$amount = number_format( (float) $amount, cryptoniq_get_coin_data($coin_ticker, 'decimal'), '.', '' );
			
			$coin_ticker_webhook = $coin_ticker;
			
			if ($coin_ticker == 'BNB' || cryptoniq_get_coin_data($coin_ticker, 'parent') == 'BNB') {
				// coin ticker is BSC in Tatum
				$coin_ticker_webhook = 'BSC';
			}
			
			if ($coin_ticker == 'TRX') {
				// coin ticker is TRON in Tatum
				$coin_ticker_webhook = 'TRON';
			}
			
			if ( strpos( $coin_ticker, 'USDT' ) !== false || strpos( $coin_ticker, 'USDC' ) !== false) {				
				if ($type !== 'token' && $type !== 'trc20') {
					continue;
				}
				
				$coin_chain = cryptoniq_get_coin_data($coin_ticker, 'chain');
				$coin_contract = strtolower(cryptoniq_get_coin_data($coin_ticker, 'contract'));
				$chain = strtolower(sanitize_text_field($data['chain']));
				
				if ($coin_ticker === 'USDT_SOL' || $coin_ticker === 'USDC_SOL' ||$coin_ticker === 'USDT_TRX') {
					$counterAddress = $address;
				} else {
					$counterAddress = strtolower(sanitize_text_field($data['counterAddress']));
				}
				
				if ($coin_ticker === 'USDT_TRX') {					
					if ($type !== 'trc20') {
						continue;
					}
					
					$coin_contract = $coin_wallet;
					$asset = strtolower(sanitize_text_field($data['address']));
				}
					
				if (
					$coin_contract === $asset &&
					$coin_chain === $chain &&
					$coin_wallet === $counterAddress &&
					$coin_amount === $amount
				) {
					$found = true;
					$process = ($timestamp >= $time_start && $timestamp <= $time_end);
				}
			} else {				
				if ($type !== 'native') {
					continue;
				}
				
				if (
					$coin_ticker_webhook === $asset &&
					$coin_wallet === $address &&
					$coin_amount === $amount
				) {
					$found = true;
					$process = ($timestamp >= $time_start && $timestamp <= $time_end);
				}
			}
			
			if ($found) {
				if ($process) {
					Cryptoniq_AJAX::order_status_update($order_id, $txid, $order_status);
				} else {
					Cryptoniq_AJAX::order_status_update($order_id, '', 'failed');
				}
				
				break;
			}
		}
		
		if (!$found) {
		}
	}
}