<?php
/**
 * Zano Transaction Handler
 *
 * Handles asset-specific transaction completion and storage
 *
 * @package AnyCoin_Payment_Gateway
 */

defined( 'ABSPATH' ) || exit;

/**
 * AnyCoin Transaction Handler utilities.
 *
 * @package AnyCoin_Payment_Gateway
 */
class AnyCoin_Transaction_Handler {

	/**
	 * Internal logger wrapper using WooCommerce logger.
	 *
	 * @param string $level   Log level (emergency|alert|critical|error|warning|notice|info|debug).
	 * @param string $message Log message.
	 * @param array  $context Context array for logger.
	 */
	private static function log( $level, $message, array $context = [] ) {
		if ( function_exists( 'wc_get_logger' ) ) {
			$logger = wc_get_logger();
			$logger->log( $level, $message, array_merge( [ 'source' => 'anycoin-payment-gateway' ], $context ) );
		}
	}

	/**
	 * Process payment completion with asset information.
	 *
	 * @param int          $order_id  Order ID.
	 * @param int          $payment_id Payment record ID.
	 * @param string       $asset_id  Asset ID.
	 * @param float|string $amount   Asset amount.
	 * @param string|null  $tx_hash   Transaction hash.
	 * @return bool True on success.
	 */
	public static function complete_payment( $order_id, $payment_id, $asset_id, $amount, $tx_hash = null ) {
		global $wpdb;

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return false;
		}

		$asset_name   = AnyCoin_Constants::ASSET_NAMES[ $asset_id ] ?? null;
		$asset_symbol = AnyCoin_Constants::ASSET_NAMES[ $asset_id ] ?? null;
		if ( ! $asset_name ) {
			self::log( 'warning', 'Unknown asset ID: ' . $asset_id );
			return false;
		}

		AnyCoin_Database_Manager::update_payment(
			(int) $payment_id,
			[
				'status'       => AnyCoin_Constants::STATUS_CONFIRMED,
				'asset_id'     => $asset_id,
				'asset_symbol' => $asset_symbol,
				'asset_amount' => $amount,
				'tx_hash'      => $tx_hash,
				'completed_at' => current_time( 'mysql' ),
			]
		);

		$order->add_order_note(
			sprintf(
				'Payment completed: %s %s (Asset ID: %s)',
				$amount,
				$asset_symbol,
				$asset_id
			)
		);

		$order->update_meta_data( '_anycoin_payment_asset_id', $asset_id );
		$order->update_meta_data( '_anycoin_payment_asset_symbol', $asset_symbol );
		$order->update_meta_data( '_anycoin_payment_asset_amount', $amount );
		$order->update_meta_data( '_anycoin_payment_tx_hash', $tx_hash );

		$order->payment_complete( $tx_hash );
		$order->save();

		return true;
	}


	/**
	 * Check if payment has expired (20 minutes without transaction hash).
	 *
	 * @param array $payment Payment record.
	 * @return bool True if expired.
	 */
	public static function is_payment_expired( $payment ) {

		if ( $payment['status'] !== 'pending' || ! empty( $payment['tx_hash'] ) ) {
			return false;
		}

		$created_time    = strtotime( $payment['created_at'] );
		$current_time    = time();
		$expiration_time = 20 * 60;

		return ( $current_time - $created_time ) > $expiration_time;
	}

	/**
	 * Mark payment as failed.
	 *
	 * @param int    $payment_id Payment record ID.
	 * @param int    $order_id   Order ID.
	 * @param string $reason     Failure reason.
	 * @return bool True.
	 */
	public static function mark_payment_as_failed( $payment_id, $order_id, $reason = 'Payment failed' ) {
		global $wpdb;

		AnyCoin_Database_Manager::update_payment(
			(int) $payment_id,
			[
				'status' => AnyCoin_Constants::STATUS_FAILED,
			]
		);

		$order = wc_get_order( $order_id );
		if ( $order ) {
			$order->update_status( 'failed', $reason );
			$order->add_order_note( $reason );
			$order->save();
		}

		return true;
	}

	/**
	 * Cleanup expired payments (runs via scheduled task)
	 */
	public static function cleanup_expired_payments() {
		global $wpdb;

		return AnyCoin_Database_Manager::delete_expired_payments( AnyCoin_Constants::DEFAULT_PAYMENT_TIMEOUT );
	}
}
