<?php
/**
 * Binance P2P Orders List
 * Admin interface to view all orders
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering to catch any errors
ob_start();

try {
    require_once '../includes/config.php';
    require_once '../includes/functions.php';
    
    // Simple admin authentication (you should implement proper authentication)
    // For now, using a simple session check
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    if (!isset($_SESSION['admin_logged_in'])) {
        $_SESSION['admin_logged_in'] = true; // Remove this and implement proper auth
    }
    
    require_login();
    
} catch (Exception $e) {
    ob_end_clean();
    die("Error loading configuration: " . $e->getMessage());
}

$page_title = "Binance P2P Orders";
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$payment_status_filter = $_GET['payment_status'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where = [];
$params = [];

if ($status_filter) {
    // Map filter values to actual database values (case-insensitive)
    $statusMap = [
        'pending' => ['PENDING'],
        'waiting_payment' => ['WAITING_PAYMENT', 'PENDING'],
        'paid' => ['BUYER_PAYED', 'PAID'],
        'completed' => ['COMPLETED'],
        'cancelled' => ['CANCELLED', 'CANCELLED_BY_SYSTEM']
    ];
    
    if (isset($statusMap[$status_filter])) {
        // Use IN clause for multiple possible values
        $placeholders = implode(',', array_fill(0, count($statusMap[$status_filter]), '?'));
        $where[] = "UPPER(order_status) IN ($placeholders)";
        foreach ($statusMap[$status_filter] as $status) {
            $params[] = strtoupper($status);
        }
    } else {
        // Fallback: case-insensitive match
        $where[] = "UPPER(order_status) = UPPER(?)";
        $params[] = $status_filter;
    }
}

if ($payment_status_filter) {
    $where[] = "payment_status = ?";
    $params[] = $payment_status_filter;
}

if ($search) {
    $where[] = "(order_no LIKE ? OR buyer_nickname LIKE ? OR buyer_user_id LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

try {
    // Get total count
    $countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM binance_p2p_orders $whereClause");
    $countStmt->execute($params);
    $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    $totalPages = ceil($total / $limit);

    // Get orders - LIMIT and OFFSET must be integers, not placeholders
    // Cast to int to ensure they're safe
    $limit = (int)$limit;
    $offset = (int)$offset;
    
    $stmt = $pdo->prepare("
        SELECT *, 
               bridge_transfer_id, 
               tx_hash, 
               tx_confirmed,
               bridge_liquidation_address,
               bridge_customer_id,
               payment_status
        FROM binance_p2p_orders 
        $whereClause
        ORDER BY created_at DESC 
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch Bridge drain statuses for orders that use liquidation addresses
    // IMPORTANT: Liquidation addresses create "drains" when crypto is received, not transfers
    // Each drain has its own state field: in_review, funds_received, payment_submitted, payment_processed, etc.
    // Note: bridge_transfer_id actually stores the liquidation_address_id (from process-payment.php line 439)
    $bridgeStatuses = [];
    $bridgeLogFile = __DIR__ . '/../logs/bridge-api-debug.log';
    
    // Ensure logs directory exists
    $logsDir = dirname($bridgeLogFile);
    if (!is_dir($logsDir)) {
        @mkdir($logsDir, 0755, true);
    }
    
    // Helper function to write to custom log file
    $writeBridgeLog = function($message) use ($bridgeLogFile) {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] $message\n";
        @file_put_contents($bridgeLogFile, $logEntry, FILE_APPEND);
        error_log($message); // Also write to PHP error log
    };
    
    // Check if Bridge API is configured and load the class
    if (defined('BRIDGE_API_KEY') && !empty(BRIDGE_API_KEY)) {
        // Load Bridge API class file
        $bridgeApiFile = __DIR__ . '/../includes/bridge-api.php';
        if (file_exists($bridgeApiFile)) {
            require_once $bridgeApiFile;
            $writeBridgeLog("Bridge API file loaded: $bridgeApiFile");
        } else {
            $writeBridgeLog("ERROR: Bridge API file not found at: $bridgeApiFile");
        }
        
        // Now check if class exists after loading
        if (class_exists('BridgeAPI')) {
            $bridge = new BridgeAPI(BRIDGE_API_KEY);
        
            // Filter orders that have liquidation addresses
            // bridge_transfer_id stores the liquidation_address_id (see process-payment.php line 439)
            $ordersWithLiquidation = array_filter($orders, function($o) { 
                return !empty($o['bridge_customer_id']) && !empty($o['bridge_transfer_id']); 
            });
            $writeBridgeLog("=== Fetching Bridge drain statuses for " . count($ordersWithLiquidation) . " order(s) with liquidation addresses ===");
            $writeBridgeLog("BRIDGE_API_KEY configured: Yes (length: " . strlen(BRIDGE_API_KEY) . ")");
            $writeBridgeLog("BRIDGE_API_URL: " . (defined('BRIDGE_API_URL') ? BRIDGE_API_URL : 'Not defined'));
            
            foreach ($orders as $order) {
                // Check if order uses liquidation address
                if (!empty($order['bridge_customer_id']) && !empty($order['bridge_transfer_id'])) {
                    try {
                        $customerId = $order['bridge_customer_id'];
                        $liquidationAddressId = $order['bridge_transfer_id']; // This is actually the liquidation_address_id
                        
                        $writeBridgeLog("Fetching drains for customer $customerId, liquidation address ID $liquidationAddressId (order {$order['order_no']})");
                        
                        // Get drains for this liquidation address
                        $drains = $bridge->getLiquidationAddressDrains($customerId, $liquidationAddressId);
                        
                        // Log raw response for debugging
                        $writeBridgeLog("Raw Bridge drains response: " . json_encode($drains, JSON_PRETTY_PRINT));
                        
                        // Check for API errors
                        if (isset($drains['error'])) {
                            $errorMsg = is_string($drains['error']) ? $drains['error'] : json_encode($drains['error']);
                            $httpCode = $drains['http_code'] ?? null;
                            $writeBridgeLog("ERROR: Bridge API error fetching drains: $errorMsg");
                            if ($httpCode) {
                                $writeBridgeLog("HTTP Code: $httpCode");
                            }
                            
                            // Handle 404 (Not Found) separately from other errors
                            if ($httpCode === 404) {
                                $bridgeStatuses[$order['id']] = 'not_found';
                                $writeBridgeLog("Liquidation address $liquidationAddressId not found in Bridge (404)");
                            } else {
                                $bridgeStatuses[$order['id']] = 'error';
                            }
                        } elseif (is_array($drains)) {
                            // Bridge API returns drains in a 'data' array: { "count": 1, "data": [{...}] }
                            $drainsArray = $drains['data'] ?? $drains; // Support both formats
                            
                            if (!empty($drainsArray) && is_array($drainsArray)) {
                                // Get the latest drain (most recent - drains are usually sorted by date)
                                $latestDrain = $drainsArray[0];
                                
                                if (isset($latestDrain['state'])) {
                                    $writeBridgeLog("SUCCESS: Found drain state '{$latestDrain['state']}' for liquidation address $liquidationAddressId");
                                    $bridgeStatuses[$order['id']] = $latestDrain['state'];
                                } else {
                                    $writeBridgeLog("WARNING: Drain response missing 'state' field.");
                                    if (is_array($latestDrain)) {
                                        $writeBridgeLog("Drain keys: " . implode(', ', array_keys($latestDrain)));
                                    }
                                    $bridgeStatuses[$order['id']] = 'unknown';
                                }
                            } elseif (empty($drainsArray)) {
                                // No drains found - crypto may not have been sent yet
                                $writeBridgeLog("INFO: No drains found for liquidation address $liquidationAddressId - crypto may not have been sent yet");
                                $bridgeStatuses[$order['id']] = 'no_drains';
                            } else {
                                $writeBridgeLog("WARNING: Drains data is not an array.");
                                $writeBridgeLog("Drains data type: " . gettype($drainsArray));
                                $bridgeStatuses[$order['id']] = 'unknown';
                            }
                        } else {
                            $writeBridgeLog("WARNING: Unexpected drains response format.");
                            $writeBridgeLog("Response type: " . gettype($drains));
                            $bridgeStatuses[$order['id']] = 'unknown';
                        }
                    } catch (Exception $e) {
                        $writeBridgeLog("EXCEPTION: Exception fetching Bridge drains: " . $e->getMessage());
                        $writeBridgeLog("Stack trace: " . $e->getTraceAsString());
                        $bridgeStatuses[$order['id']] = 'error';
                    } catch (Error $e) {
                        $writeBridgeLog("FATAL ERROR: Fatal error fetching Bridge drains: " . $e->getMessage());
                        $bridgeStatuses[$order['id']] = 'error';
                    }
                }
            }
        
            $writeBridgeLog("=== Finished fetching Bridge drain statuses ===");
        } else {
            $writeBridgeLog("ERROR: BridgeAPI class not found after loading file");
            $writeBridgeLog("File exists: " . (file_exists($bridgeApiFile) ? 'Yes' : 'No'));
            $writeBridgeLog("Class exists: " . (class_exists('BridgeAPI') ? 'Yes' : 'No'));
        }
    } else {
        $writeBridgeLog("WARNING: BRIDGE_API_KEY not configured");
        $writeBridgeLog("BRIDGE_API_KEY defined: " . (defined('BRIDGE_API_KEY') ? 'Yes' : 'No'));
        $writeBridgeLog("BRIDGE_API_KEY empty: " . (defined('BRIDGE_API_KEY') && empty(BRIDGE_API_KEY) ? 'Yes' : 'No'));
    }

    // Get statistics
    $statsStmt = $pdo->query("
        SELECT 
            COUNT(*) as total_orders,
            SUM(CASE WHEN payment_status = 'pending' THEN 1 ELSE 0 END) as pending_payments,
            SUM(CASE WHEN requires_manual_review = 1 THEN 1 ELSE 0 END) as manual_review,
            SUM(CASE WHEN payment_status = 'failed' THEN 1 ELSE 0 END) as failed_payments,
            SUM(CASE WHEN order_status = 'COMPLETED' THEN fiat_amount ELSE 0 END) as total_amount
        FROM binance_p2p_orders
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC) ?? [
        'total_orders' => 0,
        'pending_payments' => 0,
        'manual_review' => 0,
        'failed_payments' => 0,
        'total_amount' => 0
    ];
    
} catch (PDOException $e) {
    ob_end_clean();
    die("Database error: " . $e->getMessage() . "<br>Check if the table 'binance_p2p_orders' exists.");
}

// End output buffering and flush any errors
ob_end_flush();
?>
<!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;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 500;
        }
        .table {
            background: white;
        }
        .table thead {
            background-color: #f8f9fa;
        }
    </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> Binance P2P Orders
            </span>
            <div>
                <a href="statistics.php" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-bar-chart-fill"></i> Statistics
                </a>
                <a href="trade-history.php" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-clock-history"></i> Trade History
                </a>
                <a href="settings.php" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-gear"></i> Settings
                </a>
                <a href="notifications.php" class="btn btn-light btn-sm">
                    <i class="bi bi-bell"></i> Notifications
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Statistics -->
        <div class="row">
            <div class="col-md-3">
                <div class="stat-card">
                    <h6 class="text-white-50 mb-2">Total Orders (30d)</h6>
                    <h2><?php echo number_format($stats['total_orders'] ?? 0); ?></h2>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <h6 class="text-white-50 mb-2">Pending Payments</h6>
                    <h2><?php echo number_format($stats['pending_payments'] ?? 0); ?></h2>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                    <h6 class="text-white-50 mb-2">Manual Review</h6>
                    <h2><?php echo number_format($stats['manual_review'] ?? 0); ?></h2>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                    <h6 class="text-white-50 mb-2">Total Amount (30d)</h6>
                    <h2><?php echo format_currency($stats['total_amount'] ?? 0, 'EUR'); ?></h2>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Order Status</label>
                        <select name="status" class="form-select">
                            <option value="">All Statuses</option>
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="waiting_payment" <?php echo $status_filter === 'waiting_payment' ? 'selected' : ''; ?>>Waiting Payment</option>
                            <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Payment Status</label>
                        <select name="payment_status" class="form-select">
                            <option value="">All Payment Statuses</option>
                            <option value="pending" <?php echo $payment_status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo $payment_status_filter === 'processing' ? 'selected' : ''; ?>>Processing</option>
                            <option value="completed" <?php echo $payment_status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="failed" <?php echo $payment_status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" placeholder="Order No, Buyer..." value="<?php echo sanitize($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i> Filter
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Orders Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Orders (<?php echo number_format($total); ?> total)</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Order No</th>
                                <th>Buyer</th>
                                <th>Amount</th>
                                <th>Order Status</th>
                                <th>Payment Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($orders)): ?>
                                <tr>
                                    <td colspan="8" class="text-center py-5 text-muted">
                                        <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                                        <p class="mt-3">No orders found</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($orders as $order): ?>
                                    <tr>
                                        <td>
                                            <code><?php echo sanitize($order['order_no']); ?></code>
                                            <?php if ($order['requires_manual_review']): ?>
                                                <span class="badge bg-warning ms-2">Review</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?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"><?php echo sanitize($order['buyer_user_id']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <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>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo get_status_badge_class($order['order_status']); ?>">
                                                <?php echo get_order_status_display($order['order_status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo get_status_badge_class($order['payment_status']); ?>">
                                                <?php echo get_payment_status_display($order['payment_status']); ?>
                                            </span>
                                            <?php 
                                            // Check if IBAN was extracted from chat or name was translated
                                            $paymentDetails = json_decode($order['payment_details'] ?? '{}', true);
                                            $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';
                                            
                                            // Fallback: Check SYSTRAN configuration if metadata not available
                                            if (!$nameTranslated) {
                                                require_once '../includes/binance-settings.php';
                                                $settings = new BinanceP2PSettings($pdo);
                                                $systranConfigured = !empty($settings->get('systran_api_key'));
                                                $nameTranslated = $systranConfigured && !empty($paymentDetails['name'] ?? '') && 
                                                                  !empty($paymentDetails['original_name'] ?? '');
                                            }
                                            
                                            // Show feature badges
                                            if ($ibanFromChat): ?>
                                                <br><small class="text-info" title="IBAN was extracted from chat messages">
                                                    <i class="bi bi-chat-dots"></i> IBAN from Chat
                                                </small>
                                            <?php endif; ?>
                                            <?php if ($nameTranslated): ?>
                                                <br><small class="text-success" title="Name was translated to English using SYSTRAN API">
                                                    <i class="bi bi-translate"></i> Name Translated
                                                </small>
                                            <?php endif; ?>
                                            <?php 
                                            // Only show error if payment status is NOT completed
                                            // Completed orders may have error_message from earlier processing attempts
                                            if ($order['error_message'] && $order['payment_status'] !== 'completed'): ?>
                                                <br><small class="text-danger" title="<?php echo sanitize($order['error_message']); ?>">
                                                    <i class="bi bi-exclamation-triangle"></i> Error
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            // Determine Bridge status
                                            $bridgeStatus = 'Not Started';
                                            $bridgeStatusClass = 'secondary';
                                            $bridgeStatusIcon = 'bi-circle';
                                            
                                            if (!empty($order['bridge_transfer_id'])) {
                                                // Get Bridge transfer status
                                                $transferState = $bridgeStatuses[$order['id']] ?? null;
                                                
                                                if ($transferState === 'error') {
                                                    $bridgeStatus = 'API Error';
                                                    $bridgeStatusClass = 'danger';
                                                    $bridgeStatusIcon = 'bi-exclamation-triangle';
                                                } elseif ($transferState === 'not_found') {
                                                    $bridgeStatus = 'Not Found';
                                                    $bridgeStatusClass = 'warning';
                                                    $bridgeStatusIcon = 'bi-question-circle';
                                                } elseif ($transferState === 'no_drains') {
                                                    $bridgeStatus = 'No Drains';
                                                    $bridgeStatusClass = 'secondary';
                                                    $bridgeStatusIcon = 'bi-clock';
                                                } elseif ($transferState) {
                                                    // Map Bridge drain states to user-friendly status
                                                    // Drain states: in_review, funds_received, payment_submitted, payment_processed, 
                                                    //              undeliverable, returned, refunded, error, canceled
                                                    switch (strtolower($transferState)) {
                                                        case 'completed':
                                                        case 'payment_processed':
                                                            $bridgeStatus = 'Completed';
                                                            $bridgeStatusClass = 'success';
                                                            $bridgeStatusIcon = 'bi-check-circle';
                                                            break;
                                                        case 'payment_submitted':
                                                        case 'funds_received':
                                                            $bridgeStatus = 'Processing';
                                                            $bridgeStatusClass = 'info';
                                                            $bridgeStatusIcon = 'bi-hourglass-split';
                                                            break;
                                                        case 'awaiting_funds':
                                                            // Bridge is waiting to receive funds from the customer
                                                            $bridgeStatus = 'Awaiting Funds';
                                                            $bridgeStatusClass = 'warning';
                                                            $bridgeStatusIcon = 'bi-clock';
                                                            break;
                                                        case 'in_review':
                                                            $bridgeStatus = 'In Review';
                                                            $bridgeStatusClass = 'warning';
                                                            $bridgeStatusIcon = 'bi-hourglass-split';
                                                            break;
                                                        case 'failed':
                                                        case 'error':
                                                            $bridgeStatus = 'Failed';
                                                            $bridgeStatusClass = 'danger';
                                                            $bridgeStatusIcon = 'bi-x-circle';
                                                            break;
                                                        case 'canceled':
                                                        case 'cancelled':
                                                            $bridgeStatus = 'Cancelled';
                                                            $bridgeStatusClass = 'secondary';
                                                            $bridgeStatusIcon = 'bi-x-circle';
                                                            break;
                                                        case 'undeliverable':
                                                            $bridgeStatus = 'Undeliverable';
                                                            $bridgeStatusClass = 'danger';
                                                            $bridgeStatusIcon = 'bi-exclamation-triangle';
                                                            break;
                                                        case 'returned':
                                                            $bridgeStatus = 'Returned';
                                                            $bridgeStatusClass = 'warning';
                                                            $bridgeStatusIcon = 'bi-arrow-return-left';
                                                            break;
                                                        case 'refunded':
                                                            $bridgeStatus = 'Refunded';
                                                            $bridgeStatusClass = 'info';
                                                            $bridgeStatusIcon = 'bi-arrow-counterclockwise';
                                                            break;
                                                        case 'missing_return_policy':
                                                            $bridgeStatus = 'Missing Return Policy';
                                                            $bridgeStatusClass = 'warning';
                                                            $bridgeStatusIcon = 'bi-exclamation-triangle';
                                                            break;
                                                        default:
                                                            $bridgeStatus = ucfirst(str_replace('_', ' ', $transferState));
                                                            $bridgeStatusClass = 'secondary';
                                                            $bridgeStatusIcon = 'bi-question-circle';
                                                    }
                                                } else {
                                                    // Has transfer ID but couldn't fetch status
                                                    $bridgeStatus = 'Unknown';
                                                    $bridgeStatusClass = 'secondary';
                                                    $bridgeStatusIcon = 'bi-question-circle';
                                                }
                                            } elseif (!empty($order['tx_hash'])) {
                                                // Has transaction hash but no Bridge transfer ID (legacy or direct transfer)
                                                if ($order['tx_confirmed']) {
                                                    $bridgeStatus = 'TX Confirmed';
                                                    $bridgeStatusClass = 'success';
                                                    $bridgeStatusIcon = 'bi-check-circle';
                                                } else {
                                                    $bridgeStatus = 'TX Pending';
                                                    $bridgeStatusClass = 'warning';
                                                    $bridgeStatusIcon = 'bi-clock';
                                                }
                                            } elseif ($order['payment_status'] === 'processing') {
                                                $bridgeStatus = 'Processing';
                                                $bridgeStatusClass = 'info';
                                                $bridgeStatusIcon = 'bi-hourglass-split';
                                            } elseif ($order['payment_status'] === 'completed') {
                                                $bridgeStatus = 'Completed';
                                                $bridgeStatusClass = 'success';
                                                $bridgeStatusIcon = 'bi-check-circle';
                                            } elseif ($order['payment_status'] === 'failed') {
                                                $bridgeStatus = 'Failed';
                                                $bridgeStatusClass = 'danger';
                                                $bridgeStatusIcon = 'bi-x-circle';
                                            }
                                            ?>
                                            <span class="badge bg-<?php echo $bridgeStatusClass; ?>" title="Bridge Transfer Status">
                                                <i class="bi <?php echo $bridgeStatusIcon; ?>"></i> <?php echo $bridgeStatus; ?>
                                            </span>
                                            <?php if (!empty($order['bridge_transfer_id'])): ?>
                                                <br><small class="text-muted" title="Bridge Transfer ID">
                                                    <code style="font-size: 0.75rem;"><?php echo substr($order['bridge_transfer_id'], 0, 8); ?>...</code>
                                                </small>
                                            <?php endif; ?>
                                            <?php if (!empty($order['tx_hash'])): ?>
                                                <br><small class="text-muted">
                                                    <a href="https://polygonscan.com/tx/<?php echo sanitize($order['tx_hash']); ?>" 
                                                       target="_blank" 
                                                       class="text-decoration-none" 
                                                       title="View on PolygonScan">
                                                        <i class="bi bi-box-arrow-up-right"></i> TX
                                                    </a>
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php echo format_date($order['created_at']); ?>
                                        </td>
                                        <td>
                                            <a href="order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="bi bi-eye"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php if ($totalPages > 1): ?>
                <div class="card-footer">
                    <nav>
                        <ul class="pagination mb-0 justify-content-center">
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>&payment_status=<?php echo $payment_status_filter; ?>&search=<?php echo urlencode($search); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>
    </div>

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

