// Initialize cart array and payment method variable
var cart = [];
var selectedPaymentMethod = 'online'; // Default payment method
// Document ready function to ensure DOM is loaded
[Link]('DOMContentLoaded', function() {
// Initialize cart from localStorage if available
if ([Link]('vendingCart')) {
try {
cart = [Link]([Link]('vendingCart'));
updateCart();
} catch (e) {
[Link]('Error loading cart from localStorage:', e);
cart = [];
}
}
// Set total in payment modal if it exists
updatePaymentAmount();
});
function addToCart(product) {
const existingProduct = [Link](item => [Link] === [Link]);
if (existingProduct) {
[Link] += 1;
} else {
[Link]({
...product,
quantity: 1,
price_tnd: parseFloat(product.price_tnd)
});
}
updateCart();
showNotification(`${[Link]} added to cart!`);
// Save cart to localStorage
saveCart();
}
function updateCart() {
const cartItems = [Link]('cart-items');
const cartCount = [Link]('cart-count');
const totalElement = [Link]('total');
if (!cartItems || !cartCount || !totalElement) return;
[Link] = '';
[Link](item => {
const itemElement = [Link]('div');
[Link] = 'cart-item';
[Link] = `
<img src="${item.image_url}" alt="${[Link]}">
<div class="cart-item-details">
<div class="cart-item-name">${[Link]}</div>
<div class="cart-item-price">${item.price_tnd.toFixed(3)} TND</div>
<div class="cart-item-quantity">
<button onclick="updateQuantity(${[Link]}, -1)">-</button>
<span>${[Link]}</span>
<button onclick="updateQuantity(${[Link]}, 1)">+</button>
</div>
</div>
<div class="cart-item-remove" onclick="removeFromCart($
{[Link]})">×</div>
`;
[Link](itemElement);
});
[Link] = [Link]((sum, item) => sum + [Link], 0);
[Link] = calculateTotal().toFixed(3);
// Update payment amount in modal if it exists
updatePaymentAmount();
}
function updatePaymentAmount() {
const paymentAmountElement = [Link]('payment-amount');
if (paymentAmountElement) {
[Link] = calculateTotal().toFixed(3) + ' TND';
}
}
function calculateTotal() {
return [Link]((sum, item) => sum + item.price_tnd * [Link], 0);
}
function saveCart() {
[Link]('vendingCart', [Link](cart));
}
function updateQuantity(productId, change) {
const product = [Link](item => [Link] === productId);
if (product) {
[Link] += change;
if ([Link] <= 0) {
removeFromCart(productId);
} else {
updateCart();
saveCart();
}
}
}
function removeFromCart(productId) {
cart = [Link](item => [Link] !== productId);
updateCart();
saveCart();
}
function toggleCart() {
[Link]('.side-cart').[Link]('open');
[Link]('.overlay').[Link]('active');
}
function showPaymentModal() {
if ([Link] === 0) {
showNotification('Please add items to your cart first!', 'error');
return;
}
[Link]('paymentModal').[Link] = 'block';
[Link]('.overlay').[Link]('active');
// Reset payment steps to start at method selection
resetPaymentSteps();
[Link]('method-step').[Link]('hidden');
[Link]('details-step').[Link]('hidden');
[Link]('.step').forEach(step =>
[Link]('active'));
[Link]('step-0').[Link]('active');
}
function closePaymentModal() {
[Link]('paymentModal').[Link] = 'none';
[Link]('.overlay').[Link]('active');
resetPaymentSteps();
}
function selectPaymentMethod(method) {
selectedPaymentMethod = method; // Save the selected payment method
[Link]('method-step').[Link]('hidden');
[Link]('details-step').[Link]('hidden');
[Link]('step-0').[Link]('active');
[Link]('step-1').[Link]('active');
}
function proceedToPayment() {
// Validate customer details
const customerName = [Link]('customer-name').[Link]();
const customerPhone = [Link]('customer-phone').[Link]();
if (!customerName || !customerPhone) {
showNotification('Please fill in all required fields.', 'error');
return;
}
// Only show payment form for online payments
if (selectedPaymentMethod === 'online') {
[Link]('details-step').[Link]('hidden');
[Link]('payment-step').[Link]('hidden');
[Link]('step-1').[Link]('active');
[Link]('step-2').[Link]('active');
} else {
// For machine payments, skip the payment form
processPayment();
}
}
function processPayment() {
// For online payments, validate card details
if (selectedPaymentMethod === 'online') {
const cardNumber = [Link]('card-number').[Link]();
const expiry = [Link]('expiry').[Link]();
const cvv = [Link]('cvv').[Link]();
if (!cardNumber || !expiry || !cvv) {
showNotification('Please fill in all payment details.', 'error');
return;
}
}
const machineId = [Link]('body').getAttribute('data-machine-
id');
const paymentData = {
machine_id: machineId,
items: cart,
total_amount: calculateTotal(),
customer_name: [Link]('customer-name').value,
customer_phone: [Link]('customer-phone').value,
payment_method: selectedPaymentMethod // Include the payment method
};
// Show loading state
const payButton = [Link]('#payment-step button') ||
[Link]('#details-step button');
if (payButton) {
[Link] = true;
[Link] = 'Processing...';
}
fetch('[Link]', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](paymentData)
})
.then(response => [Link]())
.then(data => {
if (payButton) {
[Link] = false;
[Link] = 'Pay Now';
}
if ([Link]) {
showConfirmation(data.collection_code, data.expires_in,
data.payment_method);
// Clear cart in localStorage
[Link]('vendingCart');
} else {
showNotification([Link] || 'Payment failed. Please try again.',
'error');
}
})
.catch(error => {
[Link]('Error:', error);
showNotification('An error occurred. Please try again.', 'error');
if (payButton) {
[Link] = false;
[Link] = 'Pay Now';
}
});
}
function showConfirmation(collectionCode, expiresIn, paymentMethod) {
if (selectedPaymentMethod === 'online') {
[Link]('payment-step').[Link]('hidden');
} else {
[Link]('details-step').[Link]('hidden');
}
[Link]('confirmation-step').[Link]('hidden');
[Link]('.step').forEach(step =>
[Link]('active'));
[Link]('step-3').[Link]('active');
[Link]('collection-code').textContent = collectionCode;
// Update instructions based on payment method
if (paymentMethod === 'machine') {
[Link]('code-instructions').innerHTML =
'Go to the machine and use this code to complete your payment.<br>' +
`<span id="expiry-time">This code will expire in ${expiresIn}.</span>`;
} else {
[Link]('code-instructions').innerHTML =
'Enter this code on the vending machine keypad to collect your
items.<br>' +
`<span id="expiry-time">This code will expire in ${expiresIn}.</span>`;
}
// Clear cart after successful payment
cart = [];
updateCart();
}
function resetPaymentSteps() {
[Link]('.payment-step').forEach(step => {
[Link]('hidden');
});
[Link]('method-step').[Link]('hidden');
[Link]('.step').forEach(step => {
[Link]('active');
});
[Link]('step-0').[Link]('active');
if ([Link]('customer-details-form')) {
[Link]('customer-details-form').reset();
}
if ([Link]('payment-form')) {
[Link]('payment-form').reset();
}
// Reset payment method to default
selectedPaymentMethod = 'online';
}
function showNotification(message, type = 'success') {
const notification = [Link]('div');
[Link] = `notification ${type}`;
[Link] = message;
[Link](notification);
setTimeout(() => {
[Link]('show');
}, 10);
setTimeout(() => {
[Link]('show');
setTimeout(() => {
[Link]();
}, 300);
}, 3000);
}