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' => 'Invalid amount']); 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 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 (optional but good practice, maybe later) db()->commit(); echo json_encode(['success' => true, 'new_balance' => $new_balance]); } elseif ($action === 'withdraw') { if ($current_balance < $amount) { throw new Exception("Insufficient funds"); } $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 action"); } } catch (Exception $e) { db()->rollBack(); header('Content-Type: application/json'); echo json_encode(['success' => false, 'error' => $e->getMessage()]); }