<?php
/**
 * Test Bridge API Connection
 * Tests the Bridge API getTransfer() method
 * 
 * Usage: php api/test-bridge-api.php [transfer_id]
 * 
 * Example:
 *   php api/test-bridge-api.php 0a139ed5-799c-45d7-8712-61cd285e45fc
 */

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    die('This script can only be run from command line.');
}

$baseDir = dirname(__DIR__);
require_once $baseDir . '/includes/config.php';
require_once $baseDir . '/includes/bridge-api.php';

function testLog($message) {
    echo $message . "\n";
    error_log($message);
}

testLog("=== Bridge API Test ===");
testLog("");

// Check configuration
testLog("1. Checking Configuration:");
testLog("   BRIDGE_API_KEY defined: " . (defined('BRIDGE_API_KEY') ? 'Yes' : 'No'));
if (defined('BRIDGE_API_KEY')) {
    $keyLength = strlen(BRIDGE_API_KEY);
    $keyPreview = substr(BRIDGE_API_KEY, 0, 10) . '...' . substr(BRIDGE_API_KEY, -5);
    testLog("   BRIDGE_API_KEY length: $keyLength");
    testLog("   BRIDGE_API_KEY preview: $keyPreview");
} else {
    testLog("   ERROR: BRIDGE_API_KEY is not defined!");
    exit(1);
}

testLog("   BRIDGE_API_URL defined: " . (defined('BRIDGE_API_URL') ? 'Yes' : 'No'));
if (defined('BRIDGE_API_URL')) {
    testLog("   BRIDGE_API_URL: " . BRIDGE_API_URL);
} else {
    testLog("   ERROR: BRIDGE_API_URL is not defined!");
    exit(1);
}

testLog("");

// Get transfer ID from command line or database
$transferId = $argv[1] ?? null;

if (!$transferId) {
    testLog("2. No transfer ID provided. Fetching from database...");
    try {
        $stmt = $pdo->query("
            SELECT bridge_transfer_id, order_no 
            FROM binance_p2p_orders 
            WHERE bridge_transfer_id IS NOT NULL 
            AND bridge_transfer_id != '' 
            ORDER BY id DESC 
            LIMIT 1
        ");
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($order) {
            $transferId = $order['bridge_transfer_id'];
            testLog("   Found transfer ID: $transferId (Order: {$order['order_no']})");
        } else {
            testLog("   ERROR: No orders with bridge_transfer_id found in database.");
            testLog("   Usage: php api/test-bridge-api.php <transfer_id>");
            exit(1);
        }
    } catch (Exception $e) {
        testLog("   ERROR: Database query failed: " . $e->getMessage());
        exit(1);
    }
} else {
    testLog("2. Using provided transfer ID: $transferId");
}

testLog("");

// Test Bridge API
testLog("3. Testing Bridge API Connection:");
try {
    $bridge = new BridgeAPI(BRIDGE_API_KEY);
    testLog("   BridgeAPI instance created successfully");
    
    testLog("   Calling getTransfer('$transferId')...");
    $startTime = microtime(true);
    $transferDetails = $bridge->getTransfer($transferId);
    $endTime = microtime(true);
    $duration = round(($endTime - $startTime) * 1000, 2);
    
    testLog("   API call completed in {$duration}ms");
    testLog("");
    
    testLog("4. Response Analysis:");
    testLog("   Response type: " . gettype($transferDetails));
    
    if (is_array($transferDetails)) {
        testLog("   Response keys: " . implode(', ', array_keys($transferDetails)));
        
        // Check for errors
        if (isset($transferDetails['error'])) {
            testLog("   ❌ ERROR DETECTED:");
            testLog("      Error: " . (is_string($transferDetails['error']) ? $transferDetails['error'] : json_encode($transferDetails['error'])));
            
            if (isset($transferDetails['http_code'])) {
                testLog("      HTTP Code: {$transferDetails['http_code']}");
            }
            
            if (isset($transferDetails['full_response'])) {
                testLog("      Full Response: " . json_encode($transferDetails['full_response'], JSON_PRETTY_PRINT));
            }
            
            testLog("");
            testLog("   Troubleshooting:");
            if (isset($transferDetails['http_code'])) {
                switch ($transferDetails['http_code']) {
                    case 401:
                        testLog("   - HTTP 401: Unauthorized - Check your BRIDGE_API_KEY");
                        break;
                    case 403:
                        testLog("   - HTTP 403: Forbidden - API key may not have required permissions");
                        break;
                    case 404:
                        testLog("   - HTTP 404: Transfer not found - Verify the transfer ID is correct");
                        break;
                    case 500:
                        testLog("   - HTTP 500: Server error - Bridge API may be experiencing issues");
                        break;
                    default:
                        testLog("   - HTTP {$transferDetails['http_code']}: Unknown error");
                }
            }
        } else {
            // Check for state field
            if (isset($transferDetails['state'])) {
                testLog("   ✅ SUCCESS: Found 'state' field");
                testLog("      State: {$transferDetails['state']}");
            } elseif (isset($transferDetails['data']['state'])) {
                testLog("   ✅ SUCCESS: Found nested 'state' field");
                testLog("      State: {$transferDetails['data']['state']}");
            } else {
                testLog("   ⚠️  WARNING: No 'state' field found in response");
            }
            
            // Show full response
            testLog("");
            testLog("   Full Response:");
            testLog(json_encode($transferDetails, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
    } else {
        testLog("   ⚠️  WARNING: Response is not an array");
        testLog("   Response: " . var_export($transferDetails, true));
    }
    
} catch (Exception $e) {
    testLog("   ❌ EXCEPTION: " . $e->getMessage());
    testLog("   Stack trace: " . $e->getTraceAsString());
    exit(1);
} catch (Error $e) {
    testLog("   ❌ FATAL ERROR: " . $e->getMessage());
    testLog("   Stack trace: " . $e->getTraceAsString());
    exit(1);
}

testLog("");
testLog("=== Test Complete ===");
testLog("");
testLog("Check the log file at: " . $baseDir . "/logs/bridge-api-debug.log");
testLog("Or check PHP error log: php -i | grep error_log");

