38451-vm/api/finance.php
2026-02-18 05:09:56 +00:00

78 lines
2.5 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
session_start();
header('Content-Type: application/json');
$db = db();
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
exit;
}
$action = $_POST['action'] ?? '';
if ($action === 'recharge') {
$amount = (float)$_POST['amount'];
$symbol = $_POST['symbol'] ?? 'USDT';
$method = $_POST['method'] ?? 'Crypto';
$tx_hash = $_POST['tx_hash'] ?? '';
if ($amount <= 0) {
echo json_encode(['success' => false, 'error' => 'Invalid amount']);
exit;
}
$stmt = $db->prepare("INSERT INTO finance_requests (user_id, type, amount, symbol, payment_method, tx_hash, status) VALUES (?, 'recharge', ?, ?, ?, ?, 'pending')");
$stmt->execute([$user_id, $amount, $symbol, $method, $tx_hash]);
echo json_encode(['success' => true]);
exit;
}
if ($action === 'withdraw') {
$amount = (float)$_POST['amount'];
$symbol = $_POST['symbol'] ?? 'USDT';
$address = $_POST['address'] ?? '';
$password = $_POST['password'] ?? '';
// Validate balance
$stmt = $db->prepare("SELECT available FROM user_balances WHERE user_id = ? AND symbol = ?");
$stmt->execute([$user_id, $symbol]);
$bal = $stmt->fetchColumn();
if ($bal < $amount) {
echo json_encode(['success' => false, 'error' => 'Insufficient balance']);
exit;
}
// In a real app, validate withdrawal password here.
// For now we just proceed as requested.
$db->beginTransaction();
try {
// Deduct balance
$db->prepare("UPDATE user_balances SET available = available - ? WHERE user_id = ? AND symbol = ?")
->execute([$amount, $user_id, $symbol]);
// Record request
$stmt = $db->prepare("INSERT INTO finance_requests (user_id, type, amount, symbol, payment_details, status) VALUES (?, 'withdrawal', ?, ?, ?, 'pending')");
$stmt->execute([$user_id, $amount, $symbol, $address]);
// Add to transactions as pending
$db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'withdrawal', ?, ?, 'pending')")
->execute([$user_id, $amount, $symbol]);
$db->commit();
echo json_encode(['success' => true]);
} catch (Exception $e) {
$db->rollBack();
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
exit;
}
echo json_encode(['success' => false, 'error' => 'Invalid action']);