0) ? ($amount / $rate) : $amount; } else { // Withdrawal: amount is already in USDT (usually) $usdt_amount = $amount; // For withdrawal, we check balance first $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?"); $stmt->execute([$user_id]); $balance = (float)$stmt->fetchColumn(); if ($balance < $usdt_amount) { die("余额不足"); } // Deduct balance immediately for withdrawal $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?"); $stmt->execute([$usdt_amount, $user_id]); } $expires_at = date('Y-m-d H:i:s', strtotime('+30 minutes')); $pdo->beginTransaction(); try { // Create order with status 'matching' $stmt = $pdo->prepare("INSERT INTO fiat_orders (user_id, order_type, amount, usdt_amount, exchange_rate, currency, status, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, 'matching', ?, CURRENT_TIMESTAMP)"); $stmt->execute([$user_id, $order_type, $amount, $usdt_amount, $rate, $currency, $expires_at]); $order_id = $pdo->lastInsertId(); // Log to transactions table $desc = ($order_type === 'deposit') ? "充值申请 #$order_id ($amount $currency)" : "提现申请 #$order_id ($amount $currency)"; $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, currency, status, description) VALUES (?, ?, ?, 'USDT', 'pending', ?)"); $stmt->execute([$user_id, $order_type, ($order_type === 'deposit' ? $usdt_amount : -$usdt_amount), $desc]); // Notification message for admin/chat $type_text = ($order_type === 'deposit') ? "充值" : "提现"; $method_info = ($type === 'usdt') ? "USDT ($network)" : "法币 ($currency)"; $msg = "📢 用户发起 $type_text 请求\n金额: $amount $currency\n订单号: #$order_id\n方式: $method_info"; $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)"); $stmt->execute([$user_id, $msg]); $pdo->commit(); header("Location: chat.php"); exit; } catch (Exception $e) { $pdo->rollBack(); die("Error: " . $e->getMessage()); } } else { header("Location: index.php"); exit; }