PNG IHDR x sBIT|d pHYs + tEXtSoftware www.inkscape.org< ,tEXtComment
<?php
// Turn off error output to screen to prevent breaking headers
ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');
// 1. Check Authentication
if (!isset($_SESSION['Email'])) {
echo "<script>alert('Session expired. Please log in again.'); window.location.href='../../../index.php';</script>";
exit();
}
$user = GetMember1($_SESSION['Email']);
if (!$user) {
echo "<script>alert('User not found.'); window.location.href='../../../index.php';</script>";
exit();
}
// 2. Validate Request Method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("Location: markets.php");
exit();
}
$userId = $user['ID'];
// ==========================================
// FIX: WE NOW USE `Capital` INSTEAD OF `wallet`
// ==========================================
$userFiatBalance = floatval($user['Capital']);
// 3. Sanitize and Validate POST Data
$tradeType = isset($_POST['trade_type']) ? strtolower(trim($_POST['trade_type'])) : '';
$assetSymbol = isset($_POST['asset_symbol']) ? strtoupper(trim($_POST['asset_symbol'])) : '';
$fromAmount = isset($_POST['from_amount']) ? floatval($_POST['from_amount']) : 0;
$toAmount = isset($_POST['to_amount']) ? floatval($_POST['to_amount']) : 0;
if (empty($assetSymbol) || $fromAmount <= 0 || $toAmount <= 0 || !in_array($tradeType, ['buy', 'sell'])) {
echo "<script>alert('Invalid trade parameters. Please check your amounts.'); window.location.href='markets.php';</script>";
exit();
}
try {
// Start Database Transaction to ensure money is safely moved
$conn->begin_transaction();
// Fetch user's current crypto balance for this specific asset from user_assets table
$cryptoBalance = 0.00000000;
$stmtAsset = $conn->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND asset_symbol = ? FOR UPDATE");
$stmtAsset->bind_param("is", $userId, $assetSymbol);
$stmtAsset->execute();
$resultAsset = $stmtAsset->get_result();
if ($row = $resultAsset->fetch_assoc()) {
$cryptoBalance = floatval($row['balance']);
}
$stmtAsset->close();
// ==========================================
// LOGIC: BUYING CRYPTO (Paying with Capital)
// ==========================================
if ($tradeType === 'buy') {
if ($fromAmount > $userFiatBalance) {
$conn->rollback();
echo "<script>alert('Insufficient Capital! You only have " . $user['sym'] . number_format($userFiatBalance, 2) . " available to buy assets.'); window.location.href='markets.php';</script>";
exit();
}
// Deduct from Capital
$newFiatBalance = $userFiatBalance - $fromAmount;
// Add to Crypto Balance
$newCryptoBalance = $cryptoBalance + $toAmount;
// ==========================================
// LOGIC: SELLING CRYPTO (Receiving Capital)
// ==========================================
} else {
if ($fromAmount > $cryptoBalance) {
$conn->rollback();
echo "<script>alert('Insufficient Crypto Balance! You only have " . number_format($cryptoBalance, 8) . " " . $assetSymbol . " available to sell.'); window.location.href='markets.php';</script>";
exit();
}
// Deduct from Crypto Balance
$newCryptoBalance = $cryptoBalance - $fromAmount;
// Add to Capital
$newFiatBalance = $userFiatBalance + $toAmount;
}
// 4. Update Fiat Balance (Capital) in legacy `members` table
$stmtUpdateFiat = $conn->prepare("UPDATE members SET Capital = ? WHERE ID = ?");
$newFiatString = strval($newFiatBalance);
$stmtUpdateFiat->bind_param("si", $newFiatString, $userId);
$stmtUpdateFiat->execute();
$stmtUpdateFiat->close();
// 5. Update or Insert Crypto Balance in `user_assets` table
if ($resultAsset->num_rows > 0) {
$stmtUpdateCrypto = $conn->prepare("UPDATE user_assets SET balance = ? WHERE user_id = ? AND asset_symbol = ?");
$stmtUpdateCrypto->bind_param("dis", $newCryptoBalance, $userId, $assetSymbol);
$stmtUpdateCrypto->execute();
$stmtUpdateCrypto->close();
} else {
$stmtInsertCrypto = $conn->prepare("INSERT INTO user_assets (user_id, asset_symbol, balance) VALUES (?, ?, ?)");
$stmtInsertCrypto->bind_param("isd", $userId, $assetSymbol, $newCryptoBalance);
$stmtInsertCrypto->execute();
$stmtInsertCrypto->close();
}
// 6. Record the transaction history (Optional but recommended)
$txType = strtoupper($tradeType) . '_' . $assetSymbol;
$txMethod = "Market Spot Exchange";
$txStatus = "COMPLETED";
// For Buy: Amount is negative fiat. For Sell: Amount is positive fiat.
$txFiatAmount = ($tradeType === 'buy') ? -$fromAmount : $toAmount;
$stmtTx = $conn->prepare("INSERT INTO transactions (user_id, type, amount, method, status) VALUES (?, ?, ?, ?, ?)");
$stmtTx->bind_param("isdss", $userId, $txType, $txFiatAmount, $txMethod, $txStatus);
$stmtTx->execute();
$stmtTx->close();
// 7. Commit changes to database
$conn->commit();
// 8. Redirect with Success Message
$actionText = ($tradeType === 'buy') ? "bought" : "sold";
$successMessage = "Successfully " . $actionText . " " . $assetSymbol . "!";
echo "<script>alert('" . $successMessage . "'); window.location.href='markets.php';</script>";
} catch (Exception $e) {
$conn->rollback();
echo "<script>alert('System Error: Could not process trade.'); window.location.href='markets.php';</script>";
}
?>
b IDATxytVսϓ22 A@IR:hCiZ[v*E:WũZA ^dQeQ @ !jZ'>gsV仿$|?g)&x-E