const ProductEditor = { init() { this.bindEvents(); this.loadFontAwesome(); }, loadFontAwesome() { // Load Font Awesome from CDN const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css'; document.head.appendChild(link); }, bindEvents() { // File Upload Handler document.getElementById('jsonUpload')?.addEventListener('change', (e) => { this.handleFileUpload(e.target.files[0]); }); // Download Current Data document.getElementById('downloadJson')?.addEventListener('click', () => { this.downloadProductData(); }); }, async handleFileUpload(file) { try { if (!file) return; Utils.showLoading(); const reader = new FileReader(); reader.onload = async (e) => { try { const data = JSON.parse(e.target.result); if (this.validateProductData(data)) { await this.updateProductData(data); NotificationManager.showSuccess('อัปเดตข้อมูลสินค้าสำเร็จ'); ProductManager.loadProducts(); // Refresh product display } } catch (error) { NotificationManager.showError('ไฟล์ JSON ไม่ถูกต้อง'); console.error('JSON parse error:', error); } }; reader.readAsText(file); } catch (error) { NotificationManager.showError('เกิดข้อผิดพลาดในการอ่านไฟล์'); console.error('File upload error:', error); } finally { Utils.hideLoading(); } }, validateProductData(data) { // Basic validation if (!data.products || !Array.isArray(data.products)) { NotificationManager.showError('รูปแบบข้อมูลไม่ถูกต้อง'); return false; } // Validate each product const isValid = data.products.every(product => product.id && product.name && typeof product.price === 'number' && typeof product.available === 'boolean' ); if (!isValid) { NotificationManager.showError('ข้อมูลสินค้าไม่ครบถ้วน'); return false; } return true; }, async updateProductData(data) { try { // ในที่นี้จะเก็บข้อมูลใน localStorage // ในการใช้งานจริงควรส่งไปยัง server Storage.save('productData', data); // Update state State.products = data.products; // Emit event EventBus.emit('productsUpdated', data); return true; } catch (error) { console.error('Update product data error:', error); return false; } }, downloadProductData() { try { const data = Storage.load('productData') || { products: State.products, version: "1.0", lastUpdated: new Date().toISOString() }; const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `products_${new Date().toISOString().split('T')[0]}.json`; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); } catch (error) { NotificationManager.showError('เกิดข้อผิดพลาดในการดาวน์โหลดไฟล์'); console.error('Download error:', error); } }, createEditorModal() { return `
`; }, renderProductList() { return State.products.map(product => `${Utils.formatPrice(product.price)}