0% found this document useful (0 votes)
6 views

message (2)

The document outlines a JavaScript implementation for a vending cart system, including functionalities for adding items to the cart, updating quantities, and processing payments. It features a payment modal that allows users to select payment methods and enter customer details, with validation and error handling. The system also saves the cart state in localStorage and provides user notifications for various actions.

Uploaded by

maamourimaher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

message (2)

The document outlines a JavaScript implementation for a vending cart system, including functionalities for adding items to the cart, updating quantities, and processing payments. It features a payment modal that allows users to select payment methods and enter customer details, with validation and error handling. The system also saves the cart state in localStorage and provides user notifications for various actions.

Uploaded by

maamourimaher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

// Initialize cart array and payment method variable

var cart = [];


var selectedPaymentMethod = 'online'; // Default payment method

// Document ready function to ensure DOM is loaded


document.addEventListener('DOMContentLoaded', function() {
// Initialize cart from localStorage if available
if (localStorage.getItem('vendingCart')) {
try {
cart = JSON.parse(localStorage.getItem('vendingCart'));
updateCart();
} catch (e) {
console.error('Error loading cart from localStorage:', e);
cart = [];
}
}

// Set total in payment modal if it exists


updatePaymentAmount();
});

function addToCart(product) {
const existingProduct = cart.find(item => item.id === product.id);
if (existingProduct) {
existingProduct.quantity += 1;
} else {
cart.push({
...product,
quantity: 1,
price_tnd: parseFloat(product.price_tnd)
});
}
updateCart();
showNotification(`${product.name} added to cart!`);

// Save cart to localStorage


saveCart();
}

function updateCart() {
const cartItems = document.getElementById('cart-items');
const cartCount = document.getElementById('cart-count');
const totalElement = document.getElementById('total');

if (!cartItems || !cartCount || !totalElement) return;

cartItems.innerHTML = '';

cart.forEach(item => {
const itemElement = document.createElement('div');
itemElement.className = 'cart-item';
itemElement.innerHTML = `
<img src="${item.image_url}" alt="${item.name}">
<div class="cart-item-details">
<div class="cart-item-name">${item.name}</div>
<div class="cart-item-price">${item.price_tnd.toFixed(3)} TND</div>
<div class="cart-item-quantity">
<button onclick="updateQuantity(${item.id}, -1)">-</button>
<span>${item.quantity}</span>
<button onclick="updateQuantity(${item.id}, 1)">+</button>
</div>
</div>
<div class="cart-item-remove" onclick="removeFromCart($
{item.id})">&times;</div>
`;
cartItems.appendChild(itemElement);
});

cartCount.textContent = cart.reduce((sum, item) => sum + item.quantity, 0);


totalElement.textContent = calculateTotal().toFixed(3);

// Update payment amount in modal if it exists


updatePaymentAmount();
}

function updatePaymentAmount() {
const paymentAmountElement = document.getElementById('payment-amount');
if (paymentAmountElement) {
paymentAmountElement.textContent = calculateTotal().toFixed(3) + ' TND';
}
}

function calculateTotal() {
return cart.reduce((sum, item) => sum + item.price_tnd * item.quantity, 0);
}

function saveCart() {
localStorage.setItem('vendingCart', JSON.stringify(cart));
}

function updateQuantity(productId, change) {


const product = cart.find(item => item.id === productId);
if (product) {
product.quantity += change;
if (product.quantity <= 0) {
removeFromCart(productId);
} else {
updateCart();
saveCart();
}
}
}

function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
updateCart();
saveCart();
}

function toggleCart() {
document.querySelector('.side-cart').classList.toggle('open');
document.querySelector('.overlay').classList.toggle('active');
}

function showPaymentModal() {
if (cart.length === 0) {
showNotification('Please add items to your cart first!', 'error');
return;
}
document.getElementById('paymentModal').style.display = 'block';
document.querySelector('.overlay').classList.add('active');

// Reset payment steps to start at method selection


resetPaymentSteps();
document.getElementById('method-step').classList.remove('hidden');
document.getElementById('details-step').classList.add('hidden');
document.querySelectorAll('.step').forEach(step =>
step.classList.remove('active'));
document.getElementById('step-0').classList.add('active');
}

function closePaymentModal() {
document.getElementById('paymentModal').style.display = 'none';
document.querySelector('.overlay').classList.remove('active');
resetPaymentSteps();
}

function selectPaymentMethod(method) {
selectedPaymentMethod = method; // Save the selected payment method

document.getElementById('method-step').classList.add('hidden');
document.getElementById('details-step').classList.remove('hidden');
document.getElementById('step-0').classList.remove('active');
document.getElementById('step-1').classList.add('active');
}

function proceedToPayment() {
// Validate customer details
const customerName = document.getElementById('customer-name').value.trim();
const customerPhone = document.getElementById('customer-phone').value.trim();

if (!customerName || !customerPhone) {
showNotification('Please fill in all required fields.', 'error');
return;
}

// Only show payment form for online payments


if (selectedPaymentMethod === 'online') {
document.getElementById('details-step').classList.add('hidden');
document.getElementById('payment-step').classList.remove('hidden');
document.getElementById('step-1').classList.remove('active');
document.getElementById('step-2').classList.add('active');
} else {
// For machine payments, skip the payment form
processPayment();
}
}

function processPayment() {
// For online payments, validate card details
if (selectedPaymentMethod === 'online') {
const cardNumber = document.getElementById('card-number').value.trim();
const expiry = document.getElementById('expiry').value.trim();
const cvv = document.getElementById('cvv').value.trim();

if (!cardNumber || !expiry || !cvv) {


showNotification('Please fill in all payment details.', 'error');
return;
}
}

const machineId = document.querySelector('body').getAttribute('data-machine-


id');

const paymentData = {
machine_id: machineId,
items: cart,
total_amount: calculateTotal(),
customer_name: document.getElementById('customer-name').value,
customer_phone: document.getElementById('customer-phone').value,
payment_method: selectedPaymentMethod // Include the payment method
};

// Show loading state


const payButton = document.querySelector('#payment-step button') ||
document.querySelector('#details-step button');
if (payButton) {
payButton.disabled = true;
payButton.textContent = 'Processing...';
}

fetch('payment.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(paymentData)
})
.then(response => response.json())
.then(data => {
if (payButton) {
payButton.disabled = false;
payButton.textContent = 'Pay Now';
}

if (data.success) {
showConfirmation(data.collection_code, data.expires_in,
data.payment_method);

// Clear cart in localStorage


localStorage.removeItem('vendingCart');
} else {
showNotification(data.message || 'Payment failed. Please try again.',
'error');
}
})
.catch(error => {
console.error('Error:', error);
showNotification('An error occurred. Please try again.', 'error');

if (payButton) {
payButton.disabled = false;
payButton.textContent = 'Pay Now';
}
});
}
function showConfirmation(collectionCode, expiresIn, paymentMethod) {
if (selectedPaymentMethod === 'online') {
document.getElementById('payment-step').classList.add('hidden');
} else {
document.getElementById('details-step').classList.add('hidden');
}

document.getElementById('confirmation-step').classList.remove('hidden');
document.querySelectorAll('.step').forEach(step =>
step.classList.remove('active'));
document.getElementById('step-3').classList.add('active');
document.getElementById('collection-code').textContent = collectionCode;

// Update instructions based on payment method


if (paymentMethod === 'machine') {
document.getElementById('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 {
document.getElementById('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() {
document.querySelectorAll('.payment-step').forEach(step => {
step.classList.add('hidden');
});
document.getElementById('method-step').classList.remove('hidden');
document.querySelectorAll('.step').forEach(step => {
step.classList.remove('active');
});
document.getElementById('step-0').classList.add('active');

if (document.getElementById('customer-details-form')) {
document.getElementById('customer-details-form').reset();
}

if (document.getElementById('payment-form')) {
document.getElementById('payment-form').reset();
}

// Reset payment method to default


selectedPaymentMethod = 'online';
}

function showNotification(message, type = 'success') {


const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('show');
}, 10);

setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => {
notification.remove();
}, 300);
}, 3000);
}

You might also like