<?php
/**
 * Binance Auto Convert & Withdrawal History
 * View history of USDT to USDC conversions and withdrawals
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);
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';
} catch (Throwable $e) {
    error_log("Error loading includes in trade-history.php: " . $e->getMessage());
    die("Error loading page configuration. Please check error logs.");
}

require_login();

$page_title = "Trade & Withdrawal History";

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

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

// Build query for auto trades
$where = [];
$params = [];

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where[] = "(withdraw_address LIKE ? OR trade_order_id LIKE ? OR withdraw_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_auto_trades $whereClause");
    $countStmt->execute($params);
    $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    $totalPages = ceil($total / $limit);
    
    // Get auto trades
    $stmt = $pdo->prepare("
        SELECT * FROM binance_auto_trades 
        $whereClause
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
    ");
    $allParams = array_merge($params, [$limit, $offset]);
    $stmt->execute($allParams);
    $autoTrades = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get withdrawal history from Binance API
    $withdrawalHistory = [];
    $convertHistory = [];
    try {
        $settings = new BinanceP2PSettings($pdo);
        $apiKey = $settings->getBinanceApiKey();
        $secretKey = $settings->getBinanceSecretKey();
        
        if (!empty($apiKey) && !empty($secretKey)) {
            $binance = new BinanceP2PAPI($apiKey, $secretKey);
            
            // Get withdrawal history
            $withdrawalResponse = $binance->getWithdrawalHistory('USDC', 100);
            if (!isset($withdrawalResponse['error']) && isset($withdrawalResponse['data'])) {
                $withdrawalHistory = $withdrawalResponse['data'];
            }
            
            // Get convert trade history (last 30 days)
            $endTime = round(microtime(true) * 1000);
            $startTime = $endTime - (30 * 24 * 60 * 60 * 1000); // 30 days ago
            $convertResponse = $binance->getConvertTradeHistory($startTime, $endTime, 100);
            if (!isset($convertResponse['error']) && isset($convertResponse['list'])) {
                $convertHistory = $convertResponse['list'];
            }
        }
    } catch (Exception $e) {
        error_log("Error fetching withdrawal/convert history: " . $e->getMessage());
    }
    
    // Get statistics from binance_auto_trades table
    // Use direct query to avoid any prepare/execute issues
    $statsQuery = "
        SELECT 
            COUNT(*) as total_trades,
            COALESCE(SUM(usdt_balance), 0) as total_usdt_traded,
            COALESCE(SUM(usdc_received), 0) as total_usdc_received,
            COALESCE(SUM(withdraw_amount), 0) as total_withdrawn,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_trades,
            SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_trades
        FROM binance_auto_trades
    ";
    
    $statsStmt = $pdo->query($statsQuery);
    
    if ($statsStmt === false) {
        $errorInfo = $pdo->errorInfo();
        error_log("ERROR: Statistics query failed: " . json_encode($errorInfo));
        $stats = [
            'total_trades' => 0,
            'total_usdt_traded' => 0,
            'total_usdc_received' => 0,
            'total_withdrawn' => 0,
            'completed_trades' => 0,
            'failed_trades' => 0
        ];
    } else {
        $statsRaw = $statsStmt->fetch(PDO::FETCH_ASSOC);
        
        // Debug: Show what we got
        if (isset($_GET['debug'])) {
            error_log("DEBUG: Raw stats from query: " . json_encode($statsRaw));
        }
        
        // Check if we got any data
        if ($statsRaw === false || empty($statsRaw)) {
            error_log("WARNING: Statistics query returned false or empty");
            $stats = [
                'total_trades' => 0,
                'total_usdt_traded' => 0,
                'total_usdc_received' => 0,
                'total_withdrawn' => 0,
                'completed_trades' => 0,
                'failed_trades' => 0
            ];
        } else {
            // Convert all values to proper types
            // Handle both string and numeric values from MySQL
            $stats = [
                'total_trades' => isset($statsRaw['total_trades']) ? (int)$statsRaw['total_trades'] : 0,
                'total_usdt_traded' => isset($statsRaw['total_usdt_traded']) ? (float)$statsRaw['total_usdt_traded'] : 0.0,
                'total_usdc_received' => isset($statsRaw['total_usdc_received']) ? (float)$statsRaw['total_usdc_received'] : 0.0,
                'total_withdrawn' => isset($statsRaw['total_withdrawn']) ? (float)$statsRaw['total_withdrawn'] : 0.0,
                'completed_trades' => isset($statsRaw['completed_trades']) ? (int)$statsRaw['completed_trades'] : 0,
                'failed_trades' => isset($statsRaw['failed_trades']) ? (int)$statsRaw['failed_trades'] : 0
            ];
            
            // Debug: Show processed stats
            if (isset($_GET['debug'])) {
                error_log("DEBUG: Processed stats: " . json_encode($stats));
            }
        }
    }
    
} catch (PDOException $e) {
    error_log("Database error in trade-history.php: " . $e->getMessage());
    $autoTrades = [];
    $withdrawalHistory = [];
    $stats = [
        'total_trades' => 0,
        'total_usdt_traded' => 0,
        'total_usdc_received' => 0,
        'total_withdrawn' => 0,
        'completed_trades' => 0,
        'failed_trades' => 0
    ];
}

?>
<!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;
            border-radius: 10px;
            overflow: hidden;
        }
        .table thead {
            background: #f8f9fa;
        }
        .table tbody tr:hover {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="orders.php">
                <i class="bi bi-currency-exchange"></i> Binance P2P Admin
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="orders.php">
                            <i class="bi bi-list-ul"></i> Orders
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="statistics.php">
                            <i class="bi bi-bar-chart"></i> Statistics
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="trade-history.php">
                            <i class="bi bi-clock-history"></i> Trade History
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="settings.php">
                            <i class="bi bi-gear"></i> Settings
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <h2 class="mb-4">
            <i class="bi bi-clock-history"></i> Trade & Withdrawal History
        </h2>

        <!-- Debug Info (remove after fixing) -->
        <?php if (isset($_GET['debug'])): ?>
        <div class="alert alert-info">
            <strong>Debug Info:</strong><br>
            Total Trades: <?php echo $stats['total_trades']; ?><br>
            Total USDT Traded: <?php echo $stats['total_usdt_traded']; ?><br>
            Total USDC Received: <?php echo $stats['total_usdc_received']; ?><br>
            Total Withdrawn: <?php echo $stats['total_withdrawn']; ?><br>
            Completed Trades: <?php echo $stats['completed_trades']; ?><br>
            Failed Trades: <?php echo $stats['failed_trades']; ?><br>
            <br>
            <strong>Raw Stats Array:</strong><br>
            <pre><?php print_r($stats); ?></pre>
            <br>
            <strong>Table Check:</strong><br>
            <?php
            try {
                $testStmt = $pdo->query("SELECT COUNT(*) as count FROM binance_auto_trades");
                $testCount = $testStmt->fetch(PDO::FETCH_ASSOC);
                echo "Rows in binance_auto_trades: " . ($testCount['count'] ?? 'N/A') . "<br>";
                
                $sampleStmt = $pdo->query("SELECT * FROM binance_auto_trades LIMIT 3");
                $samples = $sampleStmt->fetchAll(PDO::FETCH_ASSOC);
                echo "Sample rows: " . count($samples) . "<br>";
                if (!empty($samples)) {
                    echo "<pre>" . print_r($samples, true) . "</pre>";
                }
            } catch (Exception $e) {
                echo "Error: " . $e->getMessage();
            }
            ?>
        </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stat-card">
                    <h6 class="text-white-50 mb-1">Total Trades</h6>
                    <h3 class="mb-0"><?php echo number_format($stats['total_trades'] ?? 0); ?></h3>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <h6 class="text-white-50 mb-1">Total USDT Traded</h6>
                    <h3 class="mb-0"><?php echo number_format($stats['total_usdt_traded'] ?? 0, 2); ?></h3>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <h6 class="text-white-50 mb-1">Total USDC Received</h6>
                    <h3 class="mb-0"><?php echo number_format($stats['total_usdc_received'] ?? 0, 2); ?></h3>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <h6 class="text-white-50 mb-1">Total Withdrawn</h6>
                    <h3 class="mb-0"><?php echo number_format($stats['total_withdrawn'] ?? 0, 2); ?></h3>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All Status</option>
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Search by address, order ID, or withdrawal ID" 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="bi bi-search"></i> Filter
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Auto Convert History -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-arrow-repeat"></i> Auto Convert History (USDT → USDC)
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($autoTrades)): ?>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> No auto conversions found.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>USDT Balance</th>
                                    <th>USDC Received</th>
                                    <th>Withdraw Amount</th>
                                    <th>Withdraw Address</th>
                                    <th>Trade Order ID</th>
                                    <th>Withdraw ID</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($autoTrades as $trade): ?>
                                    <tr>
                                        <td><?php echo format_date($trade['created_at']); ?></td>
                                        <td><?php echo number_format($trade['usdt_balance'] ?? 0, 2); ?> USDT</td>
                                        <td><?php echo number_format($trade['usdc_received'] ?? 0, 6); ?> USDC</td>
                                        <td><?php echo number_format($trade['withdraw_amount'] ?? 0, 6); ?> USDC</td>
                                        <td>
                                            <code><?php 
                                                $addr = $trade['withdraw_address'] ?? '';
                                                if ($addr) {
                                                    echo htmlspecialchars(substr($addr, 0, 10)) . '...' . htmlspecialchars(substr($addr, -8)); 
                                                } else {
                                                    echo '<span class="text-muted">-</span>';
                                                }
                                            ?></code>
                                        </td>
                                        <td>
                                            <?php if ($trade['trade_order_id']): ?>
                                                <code><?php echo htmlspecialchars($trade['trade_order_id']); ?></code>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($trade['withdraw_id']): ?>
                                                <code><?php echo htmlspecialchars($trade['withdraw_id']); ?></code>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            $statusClass = 'secondary';
                                            if ($trade['status'] === 'completed') $statusClass = 'success';
                                            elseif ($trade['status'] === 'failed') $statusClass = 'danger';
                                            ?>
                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                <?php echo strtoupper($trade['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php if ($trade['error_message']): ?>
                                        <tr>
                                            <td colspan="8" class="text-danger small">
                                                <i class="bi bi-exclamation-triangle"></i> 
                                                Error: <?php echo htmlspecialchars($trade['error_message']); ?>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center">
                                <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo htmlspecialchars($status_filter); ?>&search=<?php echo htmlspecialchars($search); ?>">
                                            Previous
                                        </a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo htmlspecialchars($status_filter); ?>&search=<?php echo htmlspecialchars($search); ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>
                                
                                <?php if ($page < $totalPages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo htmlspecialchars($status_filter); ?>&search=<?php echo htmlspecialchars($search); ?>">
                                            Next
                                        </a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Binance Withdrawal History -->
        <?php if (!empty($withdrawalHistory)): ?>
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-wallet2"></i> Binance Withdrawal History (Last 100)
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Asset</th>
                                    <th>Amount</th>
                                    <th>Network</th>
                                    <th>Address</th>
                                    <th>Transaction ID</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($withdrawalHistory as $withdrawal): ?>
                                    <tr>
                                        <td>
                                            <?php 
                                            if (isset($withdrawal['applyTime'])) {
                                                echo format_date($withdrawal['applyTime']);
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($withdrawal['coin'] ?? '-'); ?></td>
                                        <td><?php echo number_format($withdrawal['amount'] ?? 0, 6); ?></td>
                                        <td><?php echo htmlspecialchars($withdrawal['network'] ?? '-'); ?></td>
                                        <td>
                                            <code><?php 
                                                $addr = $withdrawal['address'] ?? '';
                                                if (strlen($addr) > 20) {
                                                    echo htmlspecialchars(substr($addr, 0, 10)) . '...' . htmlspecialchars(substr($addr, -8));
                                                } else {
                                                    echo htmlspecialchars($addr);
                                                }
                                            ?></code>
                                        </td>
                                        <td>
                                            <?php if (isset($withdrawal['txId']) && $withdrawal['txId']): ?>
                                                <a href="https://polygonscan.com/tx/<?php echo htmlspecialchars($withdrawal['txId']); ?>" 
                                                   target="_blank" class="text-decoration-none">
                                                    <code><?php echo htmlspecialchars(substr($withdrawal['txId'], 0, 16)) . '...'; ?></code>
                                                    <i class="bi bi-box-arrow-up-right"></i>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            $status = $withdrawal['status'] ?? 0;
                                            $statusText = 'Unknown';
                                            $statusClass = 'secondary';
                                            
                                            // Binance withdrawal status codes
                                            if ($status == 0) {
                                                $statusText = 'Email Sent';
                                                $statusClass = 'info';
                                            } elseif ($status == 1) {
                                                $statusText = 'Cancelled';
                                                $statusClass = 'warning';
                                            } elseif ($status == 2) {
                                                $statusText = 'Awaiting Approval';
                                                $statusClass = 'warning';
                                            } elseif ($status == 3) {
                                                $statusText = 'Rejected';
                                                $statusClass = 'danger';
                                            } elseif ($status == 4) {
                                                $statusText = 'Processing';
                                                $statusClass = 'info';
                                            } elseif ($status == 5) {
                                                $statusText = 'Failure';
                                                $statusClass = 'danger';
                                            } elseif ($status == 6) {
                                                $statusText = 'Completed';
                                                $statusClass = 'success';
                                            }
                                            ?>
                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                <?php echo $statusText; ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

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

