<?php
/**
 * Test Script: Send Proof Image for Specific Order
 * Usage: php test-send-image.php <order_no>
 * Example: php test-send-image.php 22830717934168264704
 */

// Enable error display for CLI debugging
if (php_sapi_name() === 'cli') {
    ini_set('display_errors', '1');
    ini_set('log_errors', '1');
    error_reporting(E_ALL);
    ini_set('output_buffering', '0');
    ini_set('session.auto_start', '0');
    
    // Clear any existing output buffers
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
} else {
    // For web requests, suppress output
    ini_set('display_errors', '0');
}

// Prevent execution via web browser (CLI only)
$isWebRequest = (
    isset($_SERVER['HTTP_HOST']) ||
    isset($_SERVER['REQUEST_METHOD']) ||
    (isset($_SERVER['SERVER_SOFTWARE']) && php_sapi_name() !== 'cli')
);

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

// Get order number from command line argument
$orderNo = $argv[1] ?? null;

if (empty($orderNo)) {
    echo "Usage: php test-send-image.php <order_no>\n";
    echo "Example: php test-send-image.php 22830717934168264704\n";
    exit(1);
}

// Immediate output to verify script is running
echo "Script started. Testing image send for order: $orderNo\n";
flush();

// Set base directory for includes
$baseDir = dirname(__DIR__);
echo "Base directory: $baseDir\n";
flush();

// Load required files
echo "Loading includes...\n";
flush();
require_once $baseDir . '/includes/config.php';
echo "✓ config.php loaded\n";
flush();
require_once $baseDir . '/includes/binance-api.php';
echo "✓ binance-api.php loaded\n";
flush();
require_once $baseDir . '/includes/binance-settings.php';
echo "✓ binance-settings.php loaded\n";
flush();
require_once $baseDir . '/includes/functions.php';
echo "✓ functions.php loaded\n";
flush();
require_once $baseDir . '/includes/websocket-client.php';
echo "✓ websocket-client.php loaded\n";
flush();

set_time_limit(60); // 1 minute timeout

// Function to log and echo for testing
function testLog($message) {
    error_log($message);
    echo $message . "\n";
}

testLog("=== Test: Send Proof Image for Order $orderNo ===");

try {
    $settings = new BinanceP2PSettings($pdo);
    
    // Get Binance API credentials
    $apiKey = $settings->getBinanceApiKey();
    $secretKey = $settings->getBinanceSecretKey();
    
    if (empty($apiKey) || empty($secretKey)) {
        testLog("ERROR: Binance API credentials not configured!");
        exit(1);
    }
    
    $binance = new BinanceP2PAPI($apiKey, $secretKey);
    
    // Get chat credentials
    testLog("Getting chat credentials from Binance...");
    $credentials = $binance->getChatCredentials();
    
    if (isset($credentials['error'])) {
        testLog("ERROR getting chat credentials: " . $credentials['error']);
        exit(1);
    }
    
    $wssUrl = $credentials['data']['chatWssUrl'] ?? null;
    $listenKey = $credentials['data']['listenKey'] ?? null;
    $listenToken = $credentials['data']['listenToken'] ?? null;
    
    if (empty($wssUrl) || empty($listenKey) || empty($listenToken)) {
        testLog("ERROR: Invalid chat credentials");
        exit(1);
    }
    
    testLog("✓ Chat credentials obtained");
    
    // Get order details from database
    testLog("Checking order in database...");
    $stmt = $pdo->prepare("
        SELECT order_no, proof_image_url, order_status, fiat_amount, fiat_currency
        FROM binance_p2p_orders
        WHERE order_no = ?
    ");
    $stmt->execute([$orderNo]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        testLog("ERROR: Order $orderNo not found in database");
        exit(1);
    }
    
    testLog("Order found:");
    testLog("  - Order No: " . $order['order_no']);
    testLog("  - Order Status: " . $order['order_status']);
    testLog("  - Proof Image URL: " . ($order['proof_image_url'] ?? 'NOT SET'));
    
    if (empty($order['proof_image_url'])) {
        testLog("ERROR: No proof_image_url found for this order");
        testLog("The image must be generated and uploaded first via process-payment.php");
        testLog("You can manually generate it by running the payment process again, or");
        testLog("check if the order has been processed with payment.");
        exit(1);
    }
    
    // Connect to WebSocket
    testLog("Connecting to WebSocket...");
    $wsClient = new BinanceWebSocketClient($wssUrl, $listenKey, $listenToken);
    
    $connected = false;
    $maxRetries = 3;
    $retryCount = 0;
    
    while ($retryCount < $maxRetries && !$connected) {
        try {
            set_time_limit(30);
            $wsClient->connect();
            $connected = $wsClient->isConnected();
            
            if ($connected) {
                testLog("✓ WebSocket connected successfully");
                break;
            }
        } catch (Exception $e) {
            $retryCount++;
            testLog("WebSocket connection attempt $retryCount failed: " . $e->getMessage());
            if ($retryCount < $maxRetries) {
                sleep(2);
            }
        }
    }
    
    if (!$connected) {
        testLog("ERROR: Could not establish WebSocket connection after $maxRetries attempts");
        exit(1);
    }
    
    // Wait a moment for connection to stabilize
    testLog("Waiting for connection to stabilize...");
    sleep(1); // Reduced from 2 to 1 second to reduce CPU usage
    
    // Send test message first
    $testMessage = "🧪 TEST: Sending proof of payment image for order $orderNo";
    testLog("Sending test message...");
    $sentTest = $wsClient->sendMessage($orderNo, $testMessage);
    
    if ($sentTest) {
        testLog("✓ Test message sent successfully");
        sleep(2);
    } else {
        testLog("⚠ Warning: Test message failed, but continuing with image...");
    }
    
    // Verify image URL is accessible first
    testLog("Verifying image URL is accessible...");
    $imageUrl = $order['proof_image_url'];
    $ch = curl_init($imageUrl);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        testLog("✓ Image URL is accessible (HTTP $httpCode)");
    } else {
        testLog("⚠️ WARNING: Image URL returned HTTP $httpCode (might not be accessible)");
    }
    
    testLog("");
    testLog("Sending proof image...");
    testLog("Image URL: " . $imageUrl);
    
    // Clear any previous errors
    $wsClient->getLastError(); // Reset error tracking
    
    // Send image URL as text message (per Binance docs)
    // According to Binance documentation, send the imageUrl in p2p chat as text
    testLog("Sending image URL as text message (per Binance documentation)...");
    $sentImage = $wsClient->sendImage($orderNo, $imageUrl);
    
    // Wait and check for errors (reduced from 5 to 2 seconds to reduce CPU usage)
    testLog("Waiting 2 seconds for Binance response...");
    sleep(2);
    $error = $wsClient->getLastError();
    if ($error) {
        testLog("⚠️ WARNING: Binance returned an error: $error");
        testLog("The image might not have been sent successfully.");
    } else {
        testLog("✓ No error received from Binance");
    }
    
    if ($sentImage && !$error) {
        testLog("✓✓✓ SUCCESS: Proof image sent successfully for order $orderNo");
        
        // Also send a confirmation message
        sleep(2);
        $confirmMessage = "✅ Proof of payment image sent above. Please check your bank account.";
        $wsClient->sendMessage($orderNo, $confirmMessage);
        testLog("✓ Confirmation message sent");
        
    } else {
        testLog("✗✗✗ FAILED: Could not send proof image for order $orderNo");
        testLog("Check WebSocket connection and image URL validity");
    }
    
    // Close connection
    $wsClient->close();
    testLog("WebSocket connection closed");
    
    testLog("=== Test Completed ===");
    
} catch (Exception $e) {
    echo "FATAL ERROR: " . $e->getMessage() . "\n";
    echo "Stack trace: " . $e->getTraceAsString() . "\n";
    error_log("FATAL ERROR: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    exit(1);
}

