38451-vm/api/finance.php
2026-02-18 07:46:54 +00:00

206 lines
8.7 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;
}
// Check frozen status
$stmt = $db->prepare("SELECT status FROM users WHERE id = ?");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() === 'frozen') {
echo json_encode(['success' => false, 'error' => 'Account frozen']);
exit;
}
$action = $_REQUEST['action'] ?? '';
if ($action === 'get_orders') {
$tab = $_GET['tab'] ?? 'spot';
$symbol = $_GET['symbol'] ?? 'BTC';
$open = [];
$settlement = [];
if ($tab === 'binary') {
// Auto-settle expired orders
$stmt = $db->prepare("SELECT o.*, u.win_loss_control as user_control FROM binary_orders o JOIN users u ON o.user_id = u.id WHERE o.user_id = ? AND o.status = 'pending' AND DATE_ADD(o.created_at, INTERVAL o.duration SECOND) <= NOW()");
$stmt->execute([$user_id]);
$expired = $stmt->fetchAll();
foreach ($expired as $o) {
$order_id = $o['id'];
$result = '';
// Simple settlement if we missed the real-time event
if ($o['control_status'] == 1 || $o['user_control'] == 1) $result = 'won';
elseif ($o['control_status'] == 2 || $o['user_control'] == 2) $result = 'lost';
else {
// Natural result fallback (randomized or tie-breaker if price history unavailable)
$result = (rand(0, 100) > 50) ? 'won' : 'lost';
}
$db->beginTransaction();
try {
$db->prepare("UPDATE binary_orders SET status = ?, settled_at = NOW() WHERE id = ?")->execute([$result, $order_id]);
if ($result === 'won') {
$win_amount = $o['amount'] + ($o['amount'] * $o['profit_rate'] / 100);
$db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = 'USDT'")->execute([$win_amount, $user_id]);
$db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_win', ?, 'USDT', 'completed')")->execute([$user_id, $win_amount]);
} else {
$db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_loss', ?, 'USDT', 'completed')")->execute([$user_id, $o['amount']]);
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
}
}
$stmt = $db->prepare("SELECT * FROM binary_orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll();
foreach ($orders as $o) {
$row = [
'id' => $o['id'],
'time' => $o['created_at'],
'pair' => $o['symbol'] . '/USDT',
'type' => 'Binary',
'side' => ($o['direction'] === 'up' || $o['direction'] === 'buy') ? 'Buy Up' : 'Buy Down',
'side_type' => ($o['direction'] === 'up' || $o['direction'] === 'buy') ? 'up' : 'down',
'price' => $o['entry_price'],
'amount' => $o['amount'],
'pnl' => $o['status'] === 'won' ? ($o['amount'] * $o['profit_rate'] / 100) : ($o['status'] === 'lost' ? -$o['amount'] : 0),
'total' => $o['status'] === 'won' ? ($o['amount'] + ($o['amount'] * $o['profit_rate'] / 100)) : ($o['status'] === 'lost' ? '0.00' : '---'),
'status' => ($o['status'] === 'won' ? 'Profit' : ($o['status'] === 'lost' ? 'Loss' : 'Executing')),
'profitRate' => $o['profit_rate']
];
if ($o['status'] === 'pending') {
$row['status'] = 'Executing';
$row['totalSeconds'] = $o['duration'];
$elapsed = time() - strtotime($o['created_at']);
$row['secondsLeft'] = max(0, $o['duration'] - $elapsed);
if ($row['secondsLeft'] > 0) $open[] = $row;
else $settlement[] = $row;
} else {
$settlement[] = $row;
}
}
} elseif ($tab === 'spot') {
$stmt = $db->prepare("SELECT * FROM spot_orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll();
foreach ($orders as $o) {
$row = [
'id' => $o['id'],
'time' => $o['created_at'],
'pair' => $o['symbol'] . '/USDT',
'type' => 'Spot',
'side' => ucfirst($o['side']),
'side_type' => $o['side'],
'price' => $o['price'],
'amount' => $o['amount'],
'total' => ($o['price'] * $o['amount']),
'status' => ucfirst($o['status'])
];
if ($o['status'] === 'pending') $open[] = $row;
else $settlement[] = $row;
}
} elseif ($tab === 'contract') {
$stmt = $db->prepare("SELECT * FROM contract_orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll();
foreach ($orders as $o) {
$row = [
'id' => $o['id'],
'time' => $o['created_at'],
'pair' => $o['symbol'] . '/USDT',
'type' => 'Contract',
'side' => ucfirst($o['direction']),
'side_type' => $o['direction'] === 'long' ? 'up' : 'down',
'price' => $o['entry_price'],
'amount' => $o['amount'],
'pnl' => $o['profit'],
'total' => ($o['amount'] / $o['leverage']) + $o['profit'],
'status' => ucfirst($o['status'])
];
if ($o['status'] === 'open') $open[] = $row;
else $settlement[] = $row;
}
}
echo json_encode(['success' => true, 'open' => $open, 'settlement' => $settlement]);
exit;
}
if ($action === 'recharge') {
$amount = (float)$_POST['amount'];
$symbol = $_POST['symbol'] ?? 'USDT';
$method = $_POST['method'] ?? 'Crypto';
$tx_hash = $_POST['tx_hash'] ?? '';
$fiat_amount = isset($_POST['fiat_amount']) ? (float)$_POST['fiat_amount'] : null;
$fiat_currency = $_POST['fiat_currency'] ?? null;
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, fiat_amount, fiat_currency, status) VALUES (?, 'recharge', ?, ?, ?, ?, ?, ?, 'pending')");
$stmt->execute([$user_id, $amount, $symbol, $method, $tx_hash, $fiat_amount, $fiat_currency]);
echo json_encode(['success' => true]);
exit;
}
if ($action === 'withdraw') {
$amount = (float)$_POST['amount'];
$symbol = $_POST['symbol'] ?? 'USDT';
$address = $_POST['address'] ?? '';
$password = $_POST['password'] ?? '';
$fiat_amount = isset($_POST['fiat_amount']) ? (float)$_POST['fiat_amount'] : null;
$fiat_currency = $_POST['fiat_currency'] ?? null;
// 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, fiat_amount, fiat_currency, status) VALUES (?, 'withdrawal', ?, ?, ?, ?, ?, 'pending')");
$stmt->execute([$user_id, $amount, $symbol, $address, $fiat_amount, $fiat_currency]);
// 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']);