<?php
/**
 * Binance P2P Order Details
 * View detailed information about a specific order
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors to users, but log them
ini_set('log_errors', 1);

try {
    require_once __DIR__ . '/../includes/config.php';
    require_once __DIR__ . '/../includes/functions.php';
    require_once __DIR__ . '/../includes/binance-api.php';
    require_once __DIR__ . '/../includes/binance-settings.php';
    
    // Include bridge-api.php if it exists and constants are defined
    if (file_exists(__DIR__ . '/../includes/bridge-api.php')) {
        // Ensure BRIDGE_API_URL is defined before including bridge-api.php
        if (!defined('BRIDGE_API_URL')) {
            define('BRIDGE_API_URL', 'https://api.bridge.xyz');
        }
        require_once __DIR__ . '/../includes/bridge-api.php';
    }
} catch (Throwable $e) {
    // Catch any errors during includes
    error_log("Error loading includes in order-details.php: " . $e->getMessage());
    error_log("File: " . $e->getFile() . " Line: " . $e->getLine());
    die("Error loading page configuration. Please check error logs.");
}

require_login();

$orderId = $_GET['id'] ?? null;
$orderNo = $_GET['order_no'] ?? null;

if (!$orderId && !$orderNo) {
    header('Location: orders.php');
    exit();
}

// Get order from database
if ($orderId) {
    $stmt = $pdo->prepare("SELECT * FROM binance_p2p_orders WHERE id = ?");
    $stmt->execute([$orderId]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM binance_p2p_orders WHERE order_no = ?");
    $stmt->execute([$orderNo]);
}
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    header('Location: orders.php');
    exit();
}

// Get payment details
$paymentDetails = $order['payment_details'] ? json_decode($order['payment_details'], true) : [];

// Get Bridge transfer details if available
$bridgeTransfer = null;
$bridgeTransferError = null;
if ($order['bridge_transfer_id']) {
    // Check if Bridge API is available
    if (!class_exists('BridgeAPI')) {
        $bridgeTransferError = "Bridge API class not available";
    } elseif (!defined('BRIDGE_API_KEY') || empty(BRIDGE_API_KEY)) {
        $bridgeTransferError = "Bridge API key not configured";
    } elseif (!defined('BRIDGE_API_URL')) {
        $bridgeTransferError = "Bridge API URL not configured";
    } else {
        try {
            $bridge = new BridgeAPI(BRIDGE_API_KEY);
            $bridgeTransfer = $bridge->getTransferDetails($order['bridge_transfer_id']);
            
            // Check if there's an error in the response
            if (isset($bridgeTransfer['error'])) {
                $bridgeTransferError = $bridgeTransfer['error'];
                $bridgeTransfer = null; // Don't display transfer details if there's an error
            }
        } catch (Exception $e) {
            // If Bridge API call fails, log error but don't crash the page
            error_log("Error fetching Bridge transfer details: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            $bridgeTransferError = "Unable to fetch transfer details: " . $e->getMessage();
            $bridgeTransfer = null;
        } catch (Error $e) {
            // Catch fatal errors (like undefined constants)
            error_log("Fatal error fetching Bridge transfer details: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            $bridgeTransferError = "Configuration error: " . $e->getMessage();
            $bridgeTransfer = null;
        }
    }
}

$page_title = "Order Details - " . $order['order_no'];

// Get flash messages
$success = $_SESSION['success'] ?? null;
$error = $_SESSION['error'] ?? null;
$warning = $_SESSION['warning'] ?? null;
unset($_SESSION['success'], $_SESSION['error'], $_SESSION['warning']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f5f5f5;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .info-row {
            padding: 12px 0;
            border-bottom: 1px solid #eee;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #666;
            font-size: 0.9rem;
        }
        .info-value {
            color: #333;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="bi bi-currency-bitcoin"></i> Order Details
            </span>
            <a href="orders.php" class="btn btn-light btn-sm">
                <i class="bi bi-arrow-left"></i> Back to Orders
            </a>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <?php if ($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bi bi-check-circle"></i> <?php echo htmlspecialchars($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bi bi-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($warning): ?>
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
                <i class="bi bi-exclamation-triangle"></i> <?php echo htmlspecialchars($warning); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-8">
                <!-- Order Information -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Order Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="info-row">
                            <div class="info-label">Order Number</div>
                            <div class="info-value"><code><?php echo sanitize($order['order_no']); ?></code></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Order Status</div>
                            <div class="info-value">
                                <span class="badge bg-<?php echo get_status_badge_class($order['order_status']); ?>">
                                    <?php echo get_order_status_display($order['order_status']); ?>
                                </span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Payment Status</div>
                            <div class="info-value">
                                <span class="badge bg-<?php echo get_status_badge_class($order['payment_status']); ?>">
                                    <?php echo get_payment_status_display($order['payment_status']); ?>
                                </span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Amount</div>
                            <div class="info-value">
                                <strong><?php echo format_currency($order['fiat_amount'], $order['fiat_currency']); ?></strong>
                                <br><small class="text-muted"><?php echo $order['crypto_amount']; ?> <?php echo $order['crypto_currency']; ?></small>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Buyer</div>
                            <div class="info-value">
                                <?php 
                                // Extract sellerNickname from raw data (this is the counterparty in BUY orders)
                                $rawData = json_decode($order['binance_raw_data'] ?? '{}', true);
                                $sellerNickname = $rawData['sellerNickname'] ?? $order['buyer_nickname'] ?? 'N/A';
                                echo sanitize($sellerNickname);
                                ?>
                                <?php if ($order['buyer_user_id']): ?>
                                    <br><small class="text-muted">ID: <?php echo sanitize($order['buyer_user_id']); ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Payment Method</div>
                            <div class="info-value"><?php echo sanitize($order['payment_method'] ?? 'N/A'); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">Created At</div>
                            <div class="info-value"><?php echo format_date($order['created_at']); ?></div>
                        </div>
                        <?php if ($order['payment_processed_at']): ?>
                            <div class="info-row">
                                <div class="info-label">Payment Processed</div>
                                <div class="info-value"><?php echo format_date($order['payment_processed_at']); ?></div>
                            </div>
                        <?php endif; ?>
                        <?php if ($order['marked_paid_at']): ?>
                            <div class="info-row">
                                <div class="info-label">Marked as Paid</div>
                                <div class="info-value"><?php echo format_date($order['marked_paid_at']); ?></div>
                            </div>
                        <?php endif; ?>
                        <?php if ($order['requires_manual_review']): ?>
                            <div class="info-row">
                                <div class="info-label">Review Required</div>
                                <div class="info-value">
                                    <span class="badge bg-warning">Yes</span>
                                    <?php if ($order['review_reason']): ?>
                                        <br><small class="text-muted"><?php echo sanitize($order['review_reason']); ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if ($order['error_message']): ?>
                            <div class="info-row">
                                <div class="info-label">Error Message</div>
                                <div class="info-value">
                                    <div class="alert alert-danger mb-0">
                                        <?php echo sanitize($order['error_message']); ?>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Payment Details -->
                <?php if (!empty($paymentDetails)): ?>
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                Buyer Payment Details
                                <?php
                                // Check if features were used
                                $hasIBAN = !empty($paymentDetails['iban'] ?? $paymentDetails['IBAN'] ?? '');
                                
                                // Check IBAN source from metadata
                                $ibanSource = $paymentDetails['iban_source'] ?? null;
                                $ibanFromChat = ($ibanSource === 'chat');
                                
                                // Check if name translation was used
                                $nameTranslated = ($paymentDetails['name_translated'] ?? 'no') === 'yes';
                                $originalName = $paymentDetails['original_name'] ?? null;
                                
                                // Check SYSTRAN configuration
                                if (!isset($settings)) {
                                    require_once __DIR__ . '/../includes/binance-settings.php';
                                    $settings = new BinanceP2PSettings($pdo);
                                }
                                $systranConfigured = !empty($settings->get('systran_api_key'));
                                
                                // Fallback detection if metadata not available
                                if (!$nameTranslated && $systranConfigured && !empty($paymentDetails['name'] ?? '') && !empty($originalName)) {
                                    $nameTranslated = true;
                                }
                                
                                if ($ibanFromChat || $nameTranslated):
                                ?>
                                    <span class="badge bg-info ms-2">
                                        <i class="bi bi-magic"></i> Auto-Processed
                                    </span>
                                <?php endif; ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if ($ibanFromChat): ?>
                                <div class="alert alert-info mb-3">
                                    <i class="bi bi-chat-dots"></i> 
                                    <strong>IBAN Extracted from Chat:</strong> The IBAN was automatically extracted from chat messages when it wasn't found in the payment page.
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($nameTranslated): ?>
                                <div class="alert alert-success mb-3">
                                    <i class="bi bi-translate"></i> 
                                    <strong>Name Translated:</strong> The account holder name was automatically translated to English using SYSTRAN Translation API before sending to Bridge.
                                    <?php if ($originalName): ?>
                                        <?php 
                                        // Get the translated name - prefer translated_name field, then check if name is different from original
                                        $translatedNameDisplay = $paymentDetails['translated_name'] ?? null;
                                        
                                        // If no translated_name field, check if name field is different from original
                                        if (empty($translatedNameDisplay)) {
                                            $currentName = $paymentDetails['name'] ?? '';
                                            if ($currentName !== $originalName && !empty($currentName)) {
                                                $translatedNameDisplay = $currentName;
                                            }
                                        }
                                        ?>
                                        <br><small>
                                            <strong>Original:</strong> <?php echo sanitize($originalName); ?> 
                                            → <strong>Translated:</strong> 
                                            <?php if ($translatedNameDisplay && $translatedNameDisplay !== $originalName): ?>
                                                <span class="text-success"><?php echo sanitize($translatedNameDisplay); ?></span>
                                            <?php else: ?>
                                                <span class="text-info">
                                                    <i class="bi bi-info-circle"></i> Translation was applied and sent to Bridge API
                                                    <br>(The translated English name was used for payment processing)
                                                </span>
                                            <?php endif; ?>
                                        </small>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php 
                            // Display payment details, but show translated name if available
                            foreach ($paymentDetails as $key => $value): 
                                // Skip metadata fields that are shown separately
                                if (in_array($key, ['iban_source', 'name_translated', 'original_name'])) {
                                    continue;
                                }
                                
                                // For name fields, show translated version if translation occurred
                                if (stripos($key, 'name') !== false && $nameTranslated && !empty($originalName)) {
                                    // If current value is the original (Arabic), show the translated version
                                    // The translated name should already be in payment_details['name'] after the fix
                                    // But for old orders, we might need to check
                                    if ($key === 'name' && $value === $originalName) {
                                        // This is an old order where name wasn't updated - skip showing original
                                        // The translated name should be shown in the alert box above
                                        continue;
                                    }
                                }
                                
                                if (!empty($value)): ?>
                                    <div class="info-row">
                                        <div class="info-label">
                                            <?php echo ucwords(str_replace('_', ' ', $key)); ?>
                                            <?php 
                                            // Add icons for special fields
                                            if (stripos($key, 'iban') !== false && $ibanFromChat): ?>
                                                <i class="bi bi-chat-dots text-info" title="Extracted from chat"></i>
                                            <?php endif; ?>
                                            <?php if (stripos($key, 'name') !== false && $nameTranslated): ?>
                                                <i class="bi bi-translate text-success" title="Translated to English"></i>
                                            <?php endif; ?>
                                        </div>
                                        <div class="info-value"><?php echo sanitize($value); ?></div>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                            
                            <!-- Show metadata fields separately -->
                            <?php if (!empty($paymentDetails['iban_source'])): ?>
                                <div class="info-row">
                                    <div class="info-label">IBAN Source</div>
                                    <div class="info-value">
                                        <span class="badge bg-<?php echo $ibanFromChat ? 'info' : 'secondary'; ?>">
                                            <?php echo sanitize(ucwords(str_replace('_', ' ', $paymentDetails['iban_source']))); ?>
                                        </span>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($nameTranslated && !empty($originalName)): ?>
                                <div class="info-row">
                                    <div class="info-label">Original Name (Before Translation)</div>
                                    <div class="info-value">
                                        <span class="text-muted"><?php echo sanitize($originalName); ?></span>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Bridge Transfer Details -->
                <?php if ($bridgeTransfer && !isset($bridgeTransfer['error'])): ?>
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">Bridge Transfer Details</h5>
                        </div>
                        <div class="card-body">
                            <div class="info-row">
                                <div class="info-label">Transfer ID</div>
                                <div class="info-value"><code><?php echo sanitize($bridgeTransfer['id'] ?? 'N/A'); ?></code></div>
                            </div>
                            <div class="info-row">
                                <div class="info-label">Status</div>
                                <div class="info-value">
                                    <span class="badge bg-success"><?php echo sanitize($bridgeTransfer['state'] ?? 'N/A'); ?></span>
                                </div>
                            </div>
                            <div class="info-row">
                                <div class="info-label">Amount</div>
                                <div class="info-value">
                                    <?php 
                                    $amount = $bridgeTransfer['amount'] ?? 0;
                                    $currency = $bridgeTransfer['source']['currency'] ?? 'USD';
                                    echo format_currency($amount, $currency);
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php elseif ($bridgeTransferError): ?>
                    <div class="card border-warning">
                        <div class="card-body">
                            <div class="alert alert-warning mb-0">
                                <i class="bi bi-exclamation-triangle"></i> 
                                <strong>Bridge Transfer:</strong> <?php echo htmlspecialchars($bridgeTransferError); ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- USDC Transaction Details -->
                <?php if ($order['tx_hash']): ?>
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">USDC Transaction</h5>
                        </div>
                        <div class="card-body">
                            <div class="info-row">
                                <div class="info-label">Transaction Hash</div>
                                <div class="info-value">
                                    <code><?php echo sanitize($order['tx_hash']); ?></code>
                                    <br>
                                    <a href="https://polygonscan.com/tx/<?php echo sanitize($order['tx_hash']); ?>" 
                                       target="_blank" class="btn btn-sm btn-outline-primary mt-2">
                                        <i class="bi bi-box-arrow-up-right"></i> View on PolygonScan
                                    </a>
                                </div>
                            </div>
                            <?php if ($order['usdc_amount_sent']): ?>
                                <div class="info-row">
                                    <div class="info-label">USDC Amount Sent</div>
                                    <div class="info-value">
                                        <strong><?php echo number_format($order['usdc_amount_sent'], 6); ?> USDC</strong>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <?php if ($order['bridge_liquidation_address']): ?>
                                <div class="info-row">
                                    <div class="info-label">Liquidation Address</div>
                                    <div class="info-value">
                                        <code><?php echo sanitize($order['bridge_liquidation_address']); ?></code>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <?php if ($order['tx_confirmed']): ?>
                                <div class="info-row">
                                    <div class="info-label">Transaction Status</div>
                                    <div class="info-value">
                                        <span class="badge bg-success">
                                            <i class="bi bi-check-circle"></i> Confirmed
                                        </span>
                                        <?php if ($order['tx_confirmations']): ?>
                                            <br><small class="text-muted"><?php echo $order['tx_confirmations']; ?> confirmations</small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="info-row">
                                    <div class="info-label">Transaction Status</div>
                                    <div class="info-value">
                                        <span class="badge bg-warning">
                                            <i class="bi bi-hourglass-split"></i> Pending
                                        </span>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <div class="col-md-4">
                <!-- Actions -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Actions</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($order['requires_manual_review']): ?>
                            <div class="alert alert-warning">
                                <i class="bi bi-exclamation-triangle"></i> This order requires manual review.
                                <br><small>Payment details (IBAN) not found in API response or chat messages. Please add them manually below.</small>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Feature Status -->
                        <div class="card border-info mb-3">
                            <div class="card-header bg-info text-white">
                                <h6 class="mb-0"><i class="bi bi-info-circle"></i> Auto-Processing Features</h6>
                            </div>
                            <div class="card-body">
                                <?php
                                // Check SYSTRAN configuration
                                if (!isset($settings)) {
                                    require_once __DIR__ . '/../includes/binance-settings.php';
                                    $settings = new BinanceP2PSettings($pdo);
                                }
                                $systranConfigured = !empty($settings->get('systran_api_key'));
                                
                                // Check if IBAN was extracted from chat
                                $hasIBAN = !empty($paymentDetails['iban'] ?? $paymentDetails['IBAN'] ?? '');
                                
                                // Check IBAN source from metadata
                                $ibanSource = $paymentDetails['iban_source'] ?? null;
                                $ibanFromChat = ($ibanSource === 'chat');
                                
                                // Check if name translation was used
                                $nameTranslated = ($paymentDetails['name_translated'] ?? 'no') === 'yes';
                                $originalName = $paymentDetails['original_name'] ?? null;
                                
                                // Fallback detection if metadata not available
                                if (!$nameTranslated && $systranConfigured && !empty($paymentDetails['name'] ?? '') && !empty($originalName)) {
                                    $nameTranslated = true;
                                }
                                ?>
                                
                                <div class="mb-2">
                                    <strong>IBAN Extraction from Chat:</strong>
                                    <?php if ($ibanFromChat): ?>
                                        <span class="badge bg-success">
                                            <i class="bi bi-check-circle"></i> Used
                                        </span>
                                        <br><small class="text-success">
                                            <i class="bi bi-chat-dots"></i> IBAN was automatically extracted from chat messages
                                        </small>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">
                                            <i class="bi bi-x-circle"></i> Not Used
                                        </span>
                                        <br><small class="text-muted">
                                            IBAN source: <?php echo sanitize($ibanSource ?? 'payment_page'); ?>
                                        </small>
                                    <?php endif; ?>
                                </div>
                                
                                <div>
                                    <strong>Name Translation (SYSTRAN):</strong>
                                    <?php if ($systranConfigured): ?>
                                        <span class="badge bg-success">
                                            <i class="bi bi-check-circle"></i> Enabled
                                        </span>
                                        <?php if ($nameTranslated): ?>
                                            <br><small class="text-success">
                                                <i class="bi bi-translate"></i> Name was translated to English
                                            </small>
                                            <?php if ($originalName): ?>
                                                <br><small class="text-muted">
                                                    Original: <?php echo sanitize($originalName); ?>
                                                </small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <br><small class="text-muted">Name was already in English or not provided</small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="badge bg-warning">
                                            <i class="bi bi-exclamation-triangle"></i> Not Configured
                                        </span>
                                        <br><small class="text-muted">
                                            <a href="settings.php">Configure SYSTRAN API key</a> to enable automatic name translation
                                        </small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($order['payment_status'] === 'failed'): ?>
                            <div class="alert alert-danger">
                                <i class="bi bi-x-circle"></i> Payment processing failed.
                            </div>
                        <?php endif; ?>
                        
                        <a href="orders.php" class="btn btn-primary w-100 mb-2">
                            <i class="bi bi-arrow-left"></i> Back to Orders
                        </a>
                    </div>
                </div>
                
                <!-- Manual Payment Details Entry -->
                <?php if ($order['requires_manual_review'] && empty($paymentDetails['iban'])): ?>
                    <div class="card border-warning">
                        <div class="card-header bg-warning text-dark">
                            <h5 class="mb-0"><i class="bi bi-exclamation-triangle"></i> Add Payment Details</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="update-payment-details.php" id="paymentDetailsForm">
                                <input type="hidden" name="order_id" value="<?php echo htmlspecialchars($order['id']); ?>">
                                <input type="hidden" name="order_no" value="<?php echo htmlspecialchars($order['order_no']); ?>">
                                
                                <div class="mb-3">
                                    <label for="iban" class="form-label">IBAN <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="iban" name="iban" 
                                           placeholder="DE89370400440532013000" required
                                           pattern="[A-Z]{2}[0-9]{2}[A-Z0-9]{4,30}"
                                           style="text-transform: uppercase;">
                                    <small class="form-text text-muted">Enter the buyer's IBAN (e.g., DE89...)</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="bank_name" class="form-label">Bank Name</label>
                                    <input type="text" class="form-control" id="bank_name" name="bank_name" 
                                           placeholder="Revolut" value="<?php echo htmlspecialchars($paymentDetails['bank_name'] ?? 'Revolut'); ?>">
                                    <small class="form-text text-muted">Default: Revolut (can be changed)</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="name" class="form-label">Account Holder Name</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           placeholder="John Doe" value="<?php echo htmlspecialchars($paymentDetails['name'] ?? ''); ?>">
                                    <small class="form-text text-muted">Enter the account holder's name (translate to English if needed)</small>
                                </div>
                                
                                <button type="submit" class="btn btn-success w-100">
                                    <i class="bi bi-check-circle"></i> Save & Process Payment
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Raw Data -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Raw Order Data</h5>
                    </div>
                    <div class="card-body">
                        <pre style="font-size: 0.8rem; max-height: 400px; overflow-y: auto;"><?php 
                            $rawData = json_decode($order['binance_raw_data'], true);
                            echo json_encode($rawData, JSON_PRETTY_PRINT);
                        ?></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

