Combining ‘earnings’ and ‘wallet’


#1

I am using a php web video script which allows Users to purchase videos successfully. The purchases are made from the amount available in the Users’ ‘wallet’ (the User can also earn compensation, which gets added to his earnings ‘balance’).

When there’s not enough available in the ‘wallet’ for the purchase, the script checks and displays a message ‘not enough money’.

I’ve added the ability where the script first checks the ‘wallet’ amount, and if empty will then check the earnings ‘balance’, and use amount from the earnings ‘balance’, for the purchase, and if neither has enough, then the “not enough money” message appears.

However, if the minimum cost of a purchase is ‘2’ and the ‘wallet’ has ‘1’ left over, it will never get used.
So, I’m trying to code it so, after checking , the ‘wallet’, and finds it doesn’t have enough, it will combine the ‘wallet’ with the earnings ‘balance’, to check if there is enough. If enough > purchase. If not enough show “not enough money”. But this code keeps showing ‘not enough money’ message, even though the ‘wallet’ has ‘4’, and the earnings ‘balance’ has ‘4’, and the purchase amount is ‘6’. I was hoping the code would combine 4 + 4 = 8 and then deduct the 6 (purchase amount).

Can you please look at my code and tell me what might be incorrect? Or suggest something that will work?

		if($wallet >= $amount){

			$wallet = (string)($wallet - $amount);
			$db->where('id', $user_id);
			$update_wallet = $db->update(T_USERS, [
				'wallet' => $wallet
			]);

}else{


if($balance + $wallet >= $amount){

$wallet = (string)($amount - $wallet);
//$balance = (string)($balance + $wallet);
$balance = (string)($balance + $wallet - $amount);
//$balance = (string)($balance - $amount);
//$wallet = '0';

$db->where('id', $user_id);
$update_user_balance = $db->update(T_USERS, [
'balance' => $balance
]);
}
}

Any additional help/comment/suggestion is appreciated


#2

So this should do it. Sorry if the syntax is wrong, but you should get the idea. You essentially need to reduce the amount by the amount in the wallet first. Once you’ve done this you can reduce the balance by the amount left after subtracting the amount in the wallet.

//Scenario (Wallet has 6, Earnings (balance) has 4 AND amount is 8)

$amount   = 8;
$wallet   = 6;
$balance  = 4;

// Combine users total cash.
$total = $wallet + $balance;

// We're good to start deducting
if ($total >= $amount) {
 	// This step reduces the left over amount by the amount in the wallet.
	$amount_less_wallet = $amount - $wallet;

	// There is now no money left in wallet.
	$wallet = 0;

	// We only subtract the amount left after taking out the money in the wallet.
	$balance = $balance - $amount_less_wallet;

	// Update user table with new values.
	$update_user_balance = $db->update(T_USERS, [
		'wallet'  => $wallet,
		'balance' => $balance
	]);
}