<?php
/**
 * Test Script: Send Payment Message for Bridge Payments
 * 
 * This script tests sending payment confirmation messages for orders
 * that have successfully sent payments via Bridge
 * 
 * Usage: php test-send-payment-message.php [order_no]
 */

// Enable error display for CLI
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();
    }
}

// Set base directory
$baseDir = dirname(__DIR__);

// Load required files
require_once $baseDir . '/includes/config.php';
require_once $baseDir . '/includes/binance-api.php';
require_once $baseDir . '/includes/binance-settings.php';
require_once $baseDir . '/includes/functions.php';
require_once $baseDir . '/includes/websocket-client.php';

echo "=== Test: Send Payment Message for Bridge Payments ===\n\n";

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

if (!$orderNo) {
    echo "Usage: php test-send-payment-message.php [order_no]\n";
    echo "\nOr run without arguments to see orders ready for messaging:\n\n";
    
    // Show orders that have Bridge payments but haven't sent messages yet
    $stmt = $pdo->prepare("
        SELECT order_no, fiat_amount, fiat_currency, order_status, payment_status,
               bridge_transfer_id, tx_hash, proof_image_url, chat_messages_sent,
               created_at, updated_at
        FROM binance_p2p_orders
        WHERE order_status = 'BUYER_PAYED'
        AND payment_status = 'completed'
        AND bridge_transfer_id IS NOT NULL
        AND bridge_transfer_id != ''
        ORDER BY updated_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($orders)) {
        echo "No orders found with completed Bridge payments.\n";
        exit(0);
    }
    
    echo "Orders with completed Bridge payments:\n";
    echo str_repeat("-", 100) . "\n";
    printf("%-20s %-12s %-15s %-15s %-10s %-15s\n", 
        "Order No", "Amount", "Currency", "Status", "Messages", "Proof Image");
    echo str_repeat("-", 100) . "\n";
    
    foreach ($orders as $order) {
        printf("%-20s %-12s %-15s %-15s %-10s %-15s\n",
            substr($order['order_no'], 0, 18),
            number_format($order['fiat_amount'], 2),
            $order['fiat_currency'],
            $order['order_status'],
            $order['chat_messages_sent'] ? 'Sent' : 'Pending',
            $order['proof_image_url'] ? 'Yes' : 'No'
        );
    }
    
    echo "\nRun: php test-send-payment-message.php [order_no]\n";
    exit(0);
}

echo "Testing message send for order: $orderNo\n\n";

// Get order details
$stmt = $pdo->prepare("
    SELECT order_no, fiat_amount, fiat_currency, order_status, payment_status,
           bridge_transfer_id, tx_hash, proof_image_url, chat_messages_sent,
           bridge_customer_id
    FROM binance_p2p_orders
    WHERE order_no = ?
");
$stmt->execute([$orderNo]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    echo "ERROR: Order $orderNo not found in database.\n";
    exit(1);
}

echo "Order Details:\n";
echo "  Order No: " . $order['order_no'] . "\n";
echo "  Amount: " . number_format($order['fiat_amount'], 2) . " " . $order['fiat_currency'] . "\n";
echo "  Order Status: " . $order['order_status'] . "\n";
echo "  Payment Status: " . $order['payment_status'] . "\n";
echo "  Bridge Transfer ID: " . ($order['bridge_transfer_id'] ?? 'N/A') . "\n";
echo "  TX Hash: " . ($order['tx_hash'] ?? 'N/A') . "\n";
echo "  Proof Image URL: " . ($order['proof_image_url'] ?? 'N/A') . "\n";
echo "  Messages Sent: " . ($order['chat_messages_sent'] ? 'Yes' : 'No') . "\n";
echo "\n";

// Check if order has completed Bridge payment
if ($order['payment_status'] !== 'completed' || empty($order['bridge_transfer_id'])) {
    echo "WARNING: Order does not have completed Bridge payment.\n";
    echo "  Payment Status: " . $order['payment_status'] . "\n";
    echo "  Bridge Transfer ID: " . ($order['bridge_transfer_id'] ?? 'N/A') . "\n";
    echo "\n";
    echo "Do you want to proceed anyway? (y/n): ";
    $handle = fopen("php://stdin", "r");
    $line = fgets($handle);
    if (trim($line) !== 'y') {
        echo "Aborted.\n";
        exit(0);
    }
}

// Load settings
$settings = new BinanceP2PSettings($pdo);
$apiKey = $settings->getBinanceApiKey();
$secretKey = $settings->getBinanceSecretKey();

if (empty($apiKey) || empty($secretKey)) {
    echo "ERROR: Binance API credentials not configured!\n";
    exit(1);
}

echo "Getting Binance API instance...\n";
$binance = new BinanceP2PAPI($apiKey, $secretKey);

// Get chat credentials
echo "Getting chat credentials from Binance...\n";
$credentials = $binance->getChatCredentials();

if (isset($credentials['error'])) {
    echo "ERROR getting chat credentials: " . $credentials['error'] . "\n";
    exit(1);
}

$wssUrl = $credentials['data']['chatWssUrl'] ?? null;
$listenKey = $credentials['data']['listenKey'] ?? null;
$listenToken = $credentials['data']['listenToken'] ?? null;

if (empty($wssUrl) || empty($listenKey) || empty($listenToken)) {
    echo "ERROR: Invalid chat credentials\n";
    exit(1);
}

echo "✓ Chat credentials obtained\n";
echo "  WSS URL: " . substr($wssUrl, 0, 50) . "...\n";
echo "  Listen Key: " . substr($listenKey, 0, 20) . "...\n";
echo "  Listen Token: " . substr($listenToken, 0, 20) . "...\n";
echo "\n";

// Create WebSocket client
echo "Creating WebSocket client...\n";
$wsClient = new BinanceWebSocketClient($wssUrl, $listenKey, $listenToken);

// Connect to WebSocket
echo "Connecting to WebSocket...\n";
echo "  WSS URL: $wssUrl\n";
echo "  Listen Key: $listenKey\n";
echo "  Listen Token: " . substr($listenToken, 0, 30) . "...\n\n";

try {
    $wsClient->connect();
    echo "✓ WebSocket connected successfully\n";
    
    // Check connection status
    $isConnected = $wsClient->isConnected();
    echo "  Connection status: " . ($isConnected ? "Connected" : "Not Connected") . "\n";
    
    // Check for immediate errors
    $immediateError = $wsClient->getLastError();
    if ($immediateError) {
        echo "  ⚠️ Immediate error after connection: $immediateError\n";
    } else {
        echo "  ✓ No immediate errors\n";
    }
    echo "\n";
} catch (Exception $e) {
    echo "ERROR: Failed to connect to WebSocket: " . $e->getMessage() . "\n";
    echo "Stack trace: " . $e->getTraceAsString() . "\n";
    exit(1);
}

// Prepare messages
$amount = $order['fiat_amount'];
$currency = $order['fiat_currency'];

$englishMessage = "✅ PAYMENT PROCESSED - ZATAM AUTOPAY BOT\n\n" .
    "Payment has been sent via (USDC → EUR).\n\n" .
    "⏱ Processing time: Up to 15 minutes to appear in your bank account\n\n" .
    "NEXT STEPS:\n\n" .
    "Check your bank account for the funds\n" .
    "Release the USDT/USDC once received\n" .
    "Do NOT release based on this message alone\n\n" .
    "⚠️ REMINDER:\n\n" .
    "I am an automated system\n" .
    "I cannot read chat responses\n" .
    "Only release after confirming funds in your account\n\n" .
    "⭐ Positive feedback appreciated after completion";

$spanishMessage = "✅ PAGO PROCESADO - ZATAM AUTOPAY BOT\n\n" .
    "El pago ha sido enviado a través (USDC → EUR).\n\n" .
    "⏱ Tiempo de procesamiento: Hasta 15 minutos para aparecer en su cuenta bancaria\n\n" .
    "PRÓXIMOS PASOS:\n\n" .
    "Verifique su cuenta bancaria por los fondos\n" .
    "Libere el USDT/USDC una vez recibido\n" .
    "NO libere solo basándose en este mensaje\n\n" .
    "⚠️ RECORDATORIO:\n\n" .
    "Soy un sistema automatizado\n" .
    "No puedo leer respuestas en el chat\n" .
    "Libere solo después de confirmar fondos en su cuenta\n\n" .
    "⭐ Comentarios positivos apreciados después de completar";

// Wait a moment for connection to fully stabilize
echo "Waiting 5 seconds for connection to stabilize and check for any errors...\n";
sleep(5);

// Check if connection is ready
if (!$wsClient->isConnected()) {
    echo "ERROR: WebSocket connection lost!\n";
    exit(1);
}

// Check for any errors before sending
$lastError = $wsClient->getLastError();
if ($lastError) {
    echo "⚠️ WARNING: Error detected before sending: $lastError\n";
    echo "This might prevent messages from being sent.\n";
}

// Send English message
echo "\nSending English message...\n";
echo "Order No: $orderNo\n";
echo "Message preview (first 150 chars): " . substr($englishMessage, 0, 150) . "...\n";
echo "Message length: " . strlen($englishMessage) . " characters\n\n";

$sentEnglish = $wsClient->sendMessage($orderNo, $englishMessage);

// Wait longer to see if we get any error responses from Binance
echo "Waiting 8 seconds to check for Binance error responses...\n";
sleep(8);

// Check for errors after sending
$lastError = $wsClient->getLastError();
if ($lastError) {
    echo "⚠️ ERROR: Binance returned error: $lastError\n";
    echo "This means the message was likely rejected by Binance.\n";
} else {
    echo "✓ No error response from Binance (message may have been accepted)\n";
}

if ($sentEnglish) {
    echo "✓ sendMessage() returned true (no immediate errors in code)\n";
    
    // Wait 2 seconds before sending proof image
    if (!empty($order['proof_image_url'])) {
        echo "Waiting 2 seconds before sending proof image...\n";
        sleep(2);
        
        echo "Sending proof of payment image...\n";
        $sentImage = $wsClient->sendImage($orderNo, $order['proof_image_url']);
        
        if ($sentImage) {
            echo "✓ Proof image sent successfully\n";
        } else {
            echo "✗ Failed to send proof image: " . $wsClient->getLastError() . "\n";
        }
    } else {
        echo "No proof image URL available for this order\n";
    }
    
    // Wait 2 seconds before sending Spanish message
    echo "Waiting 2 seconds before sending Spanish message...\n";
    sleep(2);
    
    echo "Sending Spanish message...\n";
    $sentSpanish = $wsClient->sendMessage($orderNo, $spanishMessage);
    
    if ($sentSpanish) {
        echo "✓ Spanish message sent successfully\n";
    } else {
        echo "✗ Failed to send Spanish message: " . $wsClient->getLastError() . "\n";
    }
    
    // Update database to mark messages as sent
    echo "\nUpdating database...\n";
    $updateStmt = $pdo->prepare("
        UPDATE binance_p2p_orders
        SET chat_messages_sent = 1,
            last_message_sent_at = NOW(),
            updated_at = NOW()
        WHERE order_no = ?
    ");
    $updateStmt->execute([$orderNo]);
    echo "✓ Database updated\n";
    
} else {
    echo "✗ Failed to send English message: " . $wsClient->getLastError() . "\n";
}

// Close connection
echo "\nClosing WebSocket connection...\n";
$wsClient->close();
echo "✓ Connection closed\n";

echo "\n=== Test Completed ===\n";

