38873-vm/api/wallet_transaction.php
Flatlogic Bot fb4133a854 v50
2026-02-28 22:38:01 +00:00

71 lines
2.5 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/../db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
exit;
}
$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';
$amount = (float)($_POST['amount'] ?? 0);
if ($amount <= 0) {
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Please enter a valid amount greater than zero.']);
exit;
}
try {
db()->beginTransaction();
// Fetch current balance
$stmt = db()->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
$stmt->execute([$user_id]);
$user = $stmt->fetch();
if (!$user) {
throw new Exception("User account not found.");
}
$current_balance = (float)$user['balance'];
if ($action === 'add') {
$new_balance = $current_balance + $amount;
$stmt = db()->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_balance, $user_id]);
// Log transaction
$stmt = db()->prepare("INSERT INTO wallet_transactions (user_id, amount, type, description) VALUES (?, ?, 'add', 'Added funds to wallet')");
$stmt->execute([$user_id, $amount]);
db()->commit();
echo json_encode(['success' => true, 'new_balance' => $new_balance, 'message' => 'Funds added successfully!']);
} elseif ($action === 'withdraw') {
if ($current_balance < $amount) {
throw new Exception("Insufficient funds. You only have £" . number_format($current_balance, 2) . " available.");
}
$new_balance = $current_balance - $amount;
$stmt = db()->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_balance, $user_id]);
// Log transaction
$stmt = db()->prepare("INSERT INTO wallet_transactions (user_id, amount, type, description) VALUES (?, ?, 'withdraw', 'Withdrawn funds from wallet')");
$stmt->execute([$user_id, $amount]);
db()->commit();
echo json_encode(['success' => true, 'new_balance' => $new_balance, 'message' => 'Withdrawal successful!']);
} else {
throw new Exception("Invalid action requested.");
}
} catch (Exception $e) {
if (db()->inTransaction()) {
db()->rollBack();
}
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}