Wire up wallet balance and gift cards at checkout; fix Square gift card option; fix account/rewards.php CSS; fix real PDO/schema bugs found along the way

Feature: checkout.php now lets logged-in customers apply existing wallet
balance or redeem a gift card code (which tops up wallet first, then
applies) toward their order total. Deduction is deferred to payment
success (markSquarePaymentResult in includes/square.php), never at order
creation, so an abandoned checkout never loses real wallet money - mirrors
how loyalty points already work here, unlike stock which is decremented
eagerly. payment.php gains a second Square Gift Card tab (payments.giftCard()
SDK method) alongside the card form, both hitting the same
create-square-payment.php endpoint since Square treats both source types
identically.

New api/apply-wallet-credit.php validates/quotes an amount without writing
anything - actual spend happens only via markSquarePaymentResult(). The
gift-card-to-wallet transaction logic was extracted out of
api/redeem-gift-card.php into a shared loyalty()->redeemGiftCardToWallet()
so the Wallet page and checkout both call the same code.

Also fixed three unrelated pre-existing bugs surfaced while testing this:
- loyalty.php awardPoints() reused the same named PDO parameter (:points)
  twice in one UPDATE - fails under real prepared statements, meaning
  loyalty points (and the email sent right after them) were silently never
  awarded for any order tied to a logged-in customer.
- redeemGiftCardToWallet (formerly inline in redeem-gift-card.php) referenced
  a gift_cards.updated_at column that does not exist in the schema, and used
  invalid enum values (gift_card_transactions.type=redeem,
  wallet_transactions.type=gift_card) that do not match the actual enum
  definitions - gift card redemption has likely never worked at all.
- account/rewards.php was missing the  line that loads
  account.css, unlike every other account/*.php page, so its sidebar/layout
  rendered unstyled.
This commit is contained in:
Myron Blair
2026-07-05 14:53:47 +00:00
parent 11edf3394f
commit 30daef5f74
7 changed files with 430 additions and 115 deletions
+10 -73
View File
@@ -7,6 +7,7 @@ header('Content-Type: application/json');
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/loyalty.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['error' => 'Method not allowed'], 405);
@@ -19,79 +20,15 @@ if (!CustomerAuth::isLoggedIn()) {
$customer = CustomerAuth::getFullUser();
$input = json_decode(file_get_contents('php://input'), true);
$code = strtoupper(str_replace(['-', ' '], '', trim($input['code'] ?? '')));
$result = loyalty()->redeemGiftCardToWallet($customer['customer_id'], $input['code'] ?? '');
if (empty($code) || strlen($code) < 8) {
jsonResponse(['error' => 'Invalid gift card code'], 400);
if (!$result['success']) {
jsonResponse(['error' => $result['error']], 400);
}
// Find gift card
$giftCard = db()->fetch(
"SELECT * FROM gift_cards WHERE code = :code AND is_active = 1",
['code' => $code]
);
if (!$giftCard) {
jsonResponse(['error' => 'Gift card not found or already used'], 404);
}
if ($giftCard['current_balance'] <= 0) {
jsonResponse(['error' => 'This gift card has no remaining balance'], 400);
}
if ($giftCard['expires_at'] && strtotime($giftCard['expires_at']) < time()) {
jsonResponse(['error' => 'This gift card has expired'], 400);
}
$amount = $giftCard['current_balance'];
try {
// Start transaction
db()->query("START TRANSACTION");
// Update gift card balance to 0
db()->query(
"UPDATE gift_cards SET current_balance = 0, is_active = 0, updated_at = NOW() WHERE gift_card_id = :id",
['id' => $giftCard['gift_card_id']]
);
// Log gift card transaction
db()->insert('gift_card_transactions', [
'gift_card_id' => $giftCard['gift_card_id'],
'amount' => -$amount,
'balance_after' => 0,
'type' => 'redeem',
'description' => 'Redeemed by customer: ' . $customer['email']
]);
// Add to customer wallet
$newWalletBalance = ($customer['wallet_balance'] ?? 0) + $amount;
db()->query(
"UPDATE customers SET wallet_balance = :balance, updated_at = NOW() WHERE customer_id = :id",
['balance' => $newWalletBalance, 'id' => $customer['customer_id']]
);
// Log wallet transaction
db()->insert('wallet_transactions', [
'transaction_id' => generateId('wt_'),
'customer_id' => $customer['customer_id'],
'amount' => $amount,
'balance_after' => $newWalletBalance,
'type' => 'gift_card',
'description' => 'Gift card redeemed: ' . $code
]);
db()->query("COMMIT");
jsonResponse([
'success' => true,
'amount' => $amount,
'new_balance' => $newWalletBalance,
'message' => formatCurrency($amount) . ' has been added to your wallet!'
]);
} catch (Exception $e) {
db()->query("ROLLBACK");
jsonResponse(['error' => 'Failed to redeem gift card. Please try again.'], 500);
}
jsonResponse([
'success' => true,
'amount' => $result['amount'],
'new_balance' => $result['new_balance'],
'message' => formatCurrency($result['amount']) . ' has been added to your wallet!'
]);