<?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) {
    $where[] = "order_status = ?";
    $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 * FROM binance_p2p_orders 
        $whereClause
        ORDER BY created_at DESC 
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 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="7" 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 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>

