// ตัวแปรสำหรับระบบตะกร้า
let cart = [];
let filteredProducts = [];
let productsData = [];
// โหลดข้อมูลสินค้า
async function loadProducts() {
productsData = await API.getProducts();
filteredProducts = [...productsData];
const loading = document.getElementById('loading');
setTimeout(() => {
loading.style.display = 'none';
displayProducts(filteredProducts);
}, 1000);
}
// แสดงสินค้า
function displayProducts(products) {
const productsGrid = document.getElementById('productsGrid');
if (products.length === 0) {
productsGrid.innerHTML = '
ไม่พบสินค้าที่ค้นหา
';
return;
}
productsGrid.innerHTML = products.map(product => `
${product.name}
${product.description}
${product.price.toLocaleString()} บาท
`).join('');
}
// เพิ่มสินค้าไปยังตะกร้า
function addToCart(productId) {
const product = productsData.find(p => p.id === productId);
const sizeSelect = document.getElementById(`size-${productId}`);
const colorSelect = document.getElementById(`color-${productId}`);
const selectedSize = sizeSelect.value;
const selectedColor = colorSelect.value;
if (!selectedSize || !selectedColor) {
alert('กรุณาเลือกไซส์และสีก่อนเพิ่มไปยังตะกร้า');
return;
}
const cartItemId = `${productId}-${selectedSize}-${selectedColor}`;
const existingItem = cart.find(item => item.cartItemId === cartItemId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
cartItemId,
...product,
selectedSize,
selectedColor,
quantity: 1
});
}
updateCartUI();
// Animation effect
const btn = event.target;
btn.style.background = '#2ecc71';
btn.innerHTML = ' เพิ่มแล้ว';
setTimeout(() => {
btn.style.background = 'linear-gradient(45deg, #667eea, #764ba2)';
btn.innerHTML = ' เพิ่มไปยังตะกร้า';
}, 1500);
}
// อัพเดท UI ตะกร้า
function updateCartUI() {
const cartCount = document.getElementById('cartCount');
const cartItems = document.getElementById('cartItems');
const cartTotal = document.getElementById('cartTotal');
const checkoutSection = document.getElementById('checkoutSection');
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
const totalPrice = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
cartCount.textContent = totalItems;
cartTotal.textContent = `รวม: ${totalPrice.toLocaleString()} บาท`;
if (cart.length === 0) {
cartItems.innerHTML = '';
checkoutSection.style.display = 'none';
} else {
cartItems.innerHTML = cart.map(item => `
${item.name}
ไซส์: ${item.selectedSize} | สี: ${item.selectedColor}
${item.price.toLocaleString()} บาท
${item.quantity}
`).join('');
checkoutSection.style.display = 'block';
}
}
// อัพเดทจำนวนสินค้า
function updateQuantity(cartItemId, change) {
const item = cart.find(item => item.cartItemId === cartItemId);
if (item) {
item.quantity += change;
if (item.quantity <= 0) {
removeFromCart(cartItemId);
} else {
updateCartUI();
}
}
}
// ลบสินค้าออกจากตะกร้า
function removeFromCart(cartItemId) {
cart = cart.filter(item => item.cartItemId !== cartItemId);
updateCartUI();
}
// เปิด/ปิดตะกร้า
function toggleCart() {
const modal = document.getElementById('cartModal');
modal.style.display = modal.style.display === 'block' ? 'none' : 'block';
}
// ดำเนินการชำระเงิน
function proceedToPayment() {
const form = document.getElementById('customerForm');
const name = document.getElementById('customerName').value;
const phone = document.getElementById('customerPhone').value;
const address = document.getElementById('customerAddress').value;
if (!name || !phone || !address) {
alert('กรุณากรอกข้อมูลให้ครบถ้วน');
return;
}
// สร้าง QR Code PromptPay
const totalAmount = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
generateQRCode(totalAmount);
document.getElementById('proceedToPayment').style.display = 'none';
document.getElementById('qrPayment').style.display = 'block';
document.getElementById('paymentAmount').textContent = `${totalAmount.toLocaleString()} บาท`;
}
// สร้าง QR Code PromptPay
function generateQRCode(amount) {
// ในการใช้งานจริง ควรใช้ API PromptPay QR Code Generator
// ที่นี่จะใช้ placeholder QR code
const phoneNumber = '660868142004'; // เปลี่ยนเป็นหมายเลขจริง
const qrData = `https://promptpay.io/${phoneNumber}/${amount}`;
// ใช้ QR Code API ฟรี
const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrData)}`;
document.getElementById('qrCode').src = qrCodeUrl;
}
// ยืนยันการชำระเงิน
function confirmPayment() {
const orderData = {
orderId: Date.now(),
customer: {
name: document.getElementById('customerName').value,
phone: document.getElementById('customerPhone').value,
email: document.getElementById('customerEmail').value,
address: document.getElementById('customerAddress').value
},
items: cart,
total: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0),
timestamp: new Date().toISOString(),
status: 'pending'
};
// บันทึกคำสั่งซื้อ (ในการใช้งานจริงจะส่งไป API)
console.log('Order Data:', orderData);
// แสดงข้อความสำเร็จ
document.getElementById('qrPayment').innerHTML = `
คำสั่งซื้อสำเร็จ!
หมายเลขคำสั่งซื้อ: ${orderData.orderId}
เราจะติดต่อกลับภายใน 24 ชั่วโมง
`;
// เคลียร์ตะกร้า
setTimeout(() => {
cart = [];
updateCartUI();
toggleCart();
}, 3000);
}
// ระบบค้นหาและกรอง
function filterProducts() {
const category = document.getElementById('categoryFilter').value;
const size = document.getElementById('sizeFilter').value;
const priceRange = document.getElementById('priceFilter').value;
const search = document.getElementById('searchInput').value.toLowerCase();
filteredProducts = productsData.filter(product => {
const matchCategory = !category || product.category === category;
const matchSize = !size || product.sizes.includes(size);
const matchSearch = !search || product.name.toLowerCase().includes(search) ||
product.description.toLowerCase().includes(search);
let matchPrice = true;
if (priceRange) {
const [min, max] = priceRange.split('-').map(p => p.replace('+', ''));
const minPrice = parseInt(min);
const maxPrice = max ? parseInt(max) : Infinity;
matchPrice = product.price >= minPrice && product.price <= maxPrice;
}
return matchCategory && matchSize && matchSearch && matchPrice;
});
displayProducts(filteredProducts);
}
// Event Listeners
document.getElementById('categoryFilter').addEventListener('change', filterProducts);
document.getElementById('sizeFilter').addEventListener('change', filterProducts);
document.getElementById('priceFilter').addEventListener('change', filterProducts);
document.getElementById('searchInput').addEventListener('input', filterProducts);
// ปิด modal เมื่อคลิกนอกพื้นที่
window.onclick = function(event) {
const modal = document.getElementById('cartModal');
if (event.target === modal) {
modal.style.display = 'none';
}
}
// Smooth scrolling
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// เริ่มต้นโหลดข้อมูล
window.addEventListener('DOMContentLoaded', () => {
loadProducts();
});
// API Simulation Functions (สำหรับการพัฒนาต่อ)
const API = {
// ดึงข้อมูลสินค้า
async getProducts() {
// โหลดข้อมูลจากไฟล์ products.json
const response = await fetch('api/products.json');
if (!response.ok) throw new Error('ไม่สามารถโหลดข้อมูลสินค้าได้');
const data = await response.json();
return data;
},
// บันทึกคำสั่งซื้อ
async saveOrder(orderData) {
// จำลองการส่งข้อมูลไป API
return new Promise(resolve => {
setTimeout(() => {
console.log('Order saved to API:', orderData);
resolve({success: true, orderId: orderData.orderId});
}, 1000);
});
},
// อัพเดทสถานะคำสั่งซื้อ
async updateOrderStatus(orderId, status) {
return new Promise(resolve => {
setTimeout(() => {
console.log(`Order ${orderId} status updated to: ${status}`);
resolve({success: true});
}, 500);
});
}
};