'Method not allowed'], 405); } if (!CustomerAuth::isLoggedIn()) { jsonResponse(['error' => 'Please log in to use wallet balance or a gift card'], 401); } $customer = CustomerAuth::getFullUser(); $input = json_decode(file_get_contents('php://input'), true); $orderTotal = (float) ($input['order_total'] ?? 0); if ($orderTotal <= 0) { jsonResponse(['error' => 'Invalid order total'], 400); } $giftCardCode = trim($input['gift_card_code'] ?? ''); if (!empty($giftCardCode)) { $redeemResult = loyalty()->redeemGiftCardToWallet($customer['customer_id'], $giftCardCode); if (!$redeemResult['success']) { jsonResponse(['error' => $redeemResult['error']], 400); } $walletBalance = $redeemResult['new_balance']; } else { $fresh = db()->fetch("SELECT wallet_balance FROM customers WHERE customer_id = :id", ['id' => $customer['customer_id']]); $walletBalance = (float) ($fresh['wallet_balance'] ?? 0); } $requested = isset($input['amount']) ? (float) $input['amount'] : $walletBalance; $applyAmount = max(0, round(min($requested, $walletBalance, $orderTotal), 2)); jsonResponse([ 'success' => true, 'apply_amount' => $applyAmount, 'wallet_balance' => $walletBalance, 'new_total' => round($orderTotal - $applyAmount, 2) ]);