<?php
/**
 * Transaction Confirmation Helper
 * Checks blockchain transaction status and confirmations
 */

class TransactionConfirmation {
    private $alchemyUrl;
    
    public function __construct() {
        $this->alchemyUrl = ALCHEMY_URL;
    }
    
    /**
     * Wait for transaction confirmation
     * Returns true if confirmed, false if failed or timeout
     */
    public function waitForConfirmation($txHash, $maxWaitTime = 60, $requiredConfirmations = 1) {
        $startTime = time();
        $checkInterval = 3; // Check every 3 seconds
        
        error_log("Waiting for transaction confirmation: $txHash");
        
        while ((time() - $startTime) < $maxWaitTime) {
            $status = $this->getTransactionStatus($txHash);
            
            if ($status['confirmed']) {
                if ($status['confirmations'] >= $requiredConfirmations) {
                    error_log("Transaction confirmed with {$status['confirmations']} confirmations");
                    return true;
                } else {
                    error_log("Transaction confirmed but only {$status['confirmations']} confirmations (need $requiredConfirmations)");
                }
            } elseif ($status['failed']) {
                error_log("Transaction failed: " . ($status['error'] ?? 'Unknown error'));
                return false;
            }
            
            sleep($checkInterval);
        }
        
        error_log("Transaction confirmation timeout after $maxWaitTime seconds");
        return false;
    }
    
    /**
     * Get transaction status
     */
    public function getTransactionStatus($txHash) {
        try {
            // Get transaction receipt
            $payload = [
                "jsonrpc" => "2.0",
                "method" => "eth_getTransactionReceipt",
                "params" => [$txHash],
                "id" => 1
            ];
            
            $ch = curl_init($this->alchemyUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode !== 200) {
                return ['confirmed' => false, 'failed' => false, 'error' => 'HTTP error'];
            }
            
            $data = json_decode($response, true);
            
            if (isset($data['result']) && $data['result'] !== null) {
                $receipt = $data['result'];
                $status = isset($receipt['status']) ? hexdec($receipt['status']) : null;
                
                // Get current block number to calculate confirmations
                $currentBlock = $this->getCurrentBlockNumber();
                $txBlock = isset($receipt['blockNumber']) ? hexdec($receipt['blockNumber']) : 0;
                $confirmations = $currentBlock > 0 && $txBlock > 0 ? ($currentBlock - $txBlock) : 0;
                
                if ($status === 1) {
                    return [
                        'confirmed' => true,
                        'failed' => false,
                        'confirmations' => $confirmations,
                        'blockNumber' => $txBlock
                    ];
                } elseif ($status === 0) {
                    return [
                        'confirmed' => false,
                        'failed' => true,
                        'error' => 'Transaction reverted'
                    ];
                }
            }
            
            // Transaction not found yet (pending)
            return ['confirmed' => false, 'failed' => false, 'confirmations' => 0];
            
        } catch (Exception $e) {
            error_log("Error checking transaction status: " . $e->getMessage());
            return ['confirmed' => false, 'failed' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get current block number
     */
    private function getCurrentBlockNumber() {
        try {
            $payload = [
                "jsonrpc" => "2.0",
                "method" => "eth_blockNumber",
                "params" => [],
                "id" => 1
            ];
            
            $ch = curl_init($this->alchemyUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            
            $response = curl_exec($ch);
            curl_close($ch);
            
            $data = json_decode($response, true);
            if (isset($data['result'])) {
                return hexdec($data['result']);
            }
            
            return 0;
        } catch (Exception $e) {
            error_log("Error getting current block number: " . $e->getMessage());
            return 0;
        }
    }
}

