38873-vm/api/wallet_transaction.php
Flatlogic Bot 6d5011aef2 v57
2026-02-28 22:54:59 +00:00

61 lines
1.9 KiB
PHP

<?php
header('Content-Type: application/json');
session_start();
require_once __DIR__ . '/../db/config.php';
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
exit;
}
$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';
$amount = (float)($_POST['amount'] ?? 0);
if ($amount <= 0) {
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]);
db()->commit();
echo json_encode(['success' => true, 'new_balance' => $new_balance]);
} elseif ($action === 'withdraw') {
if ($current_balance < $amount) {
throw new Exception("Insufficient funds. Your current balance is £" . number_format($current_balance, 2) . ".");
}
$new_balance = $current_balance - $amount;
$stmt = db()->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_balance, $user_id]);
db()->commit();
echo json_encode(['success' => true, 'new_balance' => $new_balance]);
} else {
throw new Exception("Invalid wallet action requested.");
}
} catch (Exception $e) {
if (db()->inTransaction()) {
db()->rollBack();
}
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}