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()]); }