// function increment() { // var qtyInput = document.getElementById('qty-input'); // qtyInput.value = parseInt(qtyInput.value) + 1; // } // function decrement() { // var qtyInput = document.getElementById('qty-input'); // if (parseInt(qtyInput.value) > 1) { // qtyInput.value = parseInt(qtyInput.value) - 1; // } // } // function deleteOrder(orderId) { // fetch('https://api.obanana.shop/api/v1/orders/' + orderId, { // method: 'DELETE' // }) // .then(response => response.json()) // .then(data => { // if (data && data !== "") { // // Order deleted successfully, update the UI // document.getElementById('order_' + data._id).remove(); // Assuming each order has a unique ID in the DOM // } else { // alert('Error deleting order: ' + data.status); // } // }) // .catch(error => console.error('Error:', error)); // } // function login(username, password, callback) { // fetch("https://api.obanana.shop/api/v1/login", { // method: "POST", // headers: { // "Content-Type": "application/json", // "X-Api-Key": "{{apiKey}}" // }, // body: JSON.stringify({ // username: username, // password: password // }) // }) // .then(response => { // if (response.ok) { // return response.json(); // } else { // throw new Error("Unable to login"); // } // }) // .then(data => { // fetch("update-token-session.php", { // method: "POST", // headers: { // "Content-Type": "application/json" // }, // body: JSON.stringify({ // token: data.token // }) // }) // .then(response => response.json()) // .then(result => { // if (result.status === 'success') { // sessionToken = data.token; // console.log("New Token:", sessionToken); // callback(sessionToken); // } else { // throw new Error("Unable to update session token"); // } // }); // }) // .catch(error => { // console.error("Error:", error.message); // }); // } // function popupAddToCart(product, productVendor, token, email, password, customer) { // // Parse the JSON string into a JavaScript object // var productObj = JSON.parse(product); // var vendorObj = JSON.parse(productVendor); // var customerObj = JSON.parse(customer); // console.log("Product Vendor JSON: " + vendorObj); // var sessionToken = token; // var productImage = productObj.product_image; // var productId = productObj._id; // var productName = productObj.product_name; // var productPrice = productObj.sale_price ? productObj.sale_price : productObj.regular_price; // var shippingFee = productObj.shipping_fee && productObj.shipping_fee !=="" ? productObj.shipping_fee: '50' ; // var productVendorId = vendorObj._id; // var vendorName = vendorObj.user_login; // var productQuantity = 1; // var customerId = customerObj[0]._id; // var customerName = customerObj[0].first_name + ' ' + customerObj[0].last_name; // // Now you can use these variables as needed // console.log("Product email: " + email); // console.log("Product password: " + password); // console.log("Product Token: " + sessionToken); // console.log("Product Image: " + productImage); // console.log("Product ID: " + productId); // console.log("Product Name: " + productName); // console.log("Product Price: " + productPrice); // console.log("Product Vendor ID: " + productVendorId); // console.log("Product Vendor Name: " + vendorName); // console.log("Product Quantity: " + productQuantity); // console.log("Customer ID: " + customerId); // console.log("Customer Name: " + customerName); // login(email, password, function(token){ // var productData = { // product: { // product_image: productImage, // product_id: productId, // name: productName, // }, // price: productPrice, // quantity: productQuantity, // vendor_id: productVendorId, // vendor_name: vendorName, // }; // var totalAmount = productData.price * productData.quantity; // var customerData = { // customer_id: customerId, // name: customerName, // }; // var existingOrder; // var orderCheckXhr = new XMLHttpRequest(); // orderCheckXhr.open("GET", "https://api.obanana.shop/api/v1/orders/customer/" + customerData.customer_id, true); // orderCheckXhr.onreadystatechange = function() { // if (orderCheckXhr.readyState === 4) { // if (orderCheckXhr.status === 200) { // var orders = JSON.parse(orderCheckXhr.responseText); // var existingItemId; // var ordersFiltered = orders.filter((e) => e.status === "CART" || e.status === "Cart") // existingOrder = ordersFiltered.find(order => order.items.some(item => item.product.product_id === productData.product.product_id)); // console.log("exist? " + existingOrder) // if (existingOrder) { // var existingItemId = existingOrder.items[0]._id; // // If the product is found in an existing CART order, update the order // updateOrder(existingOrder._id, existingItemId); // } else { // // If the product is not found or the order is not a CART, create a new order // console.log("No Order Yet!") // createNewOrder() // } // } else if (orderCheckXhr.status === 404) { // // If the customer has no orders, create a new order // console.log("No Order Yet!") // createNewOrder(); // } else { // // Handle error response from the server when checking orders // console.log("Error checking orders:", orderCheckXhr.responseText); // } // } // }; // orderCheckXhr.send(); // function createNewOrder() { // var xhr = new XMLHttpRequest(); // // Declare requestData before sending the request // var requestData = { // items: [productData], // customer: [customerData], // status: "CART", // total_amount: totalAmount, // shipping_fee: shippingFee, // }; // console.log("Request data:", requestData); // Debugging statement // // const token = ''; // xhr.open("POST", "https://api.obanana.shop/api/v1/orders", true); // xhr.setRequestHeader("Content-Type", "application/json", ); // xhr.setRequestHeader("Authorization", "Bearer " + token); // xhr.onreadystatechange = function() { // if (xhr.readyState === 4) { // if (xhr.status === 201) { // var response = JSON.parse(xhr.responseText); // console.log("Response:", response); // Debugging statement // // Update the cart dynamically // var cartList = document.querySelector(".eccart-pro-items"); // var newOrder = document.createElement("li"); // newOrder.id = `order_${response._id}`; // console.log(response) // newOrder.innerHTML = ` // // product // //
// ${response.items[0].product.name} // // Unit Price: ${response.items[0].price} // // Subtotal: ${totalAmount} //
//
-
// //
+
//
// x //
// `; // getLatestOrders() // updateCartItemCount() // cartList.appendChild(newOrder); // } else { // // Handle error response from the server // console.log("Error response from the server"); // console.log(xhr.responseText); // Log the server's response // } // } // }; // xhr.send(JSON.stringify(requestData)); // } // function getLatestOrders() { // // var customerId = '' // // Fetch the order data // fetch(`https://api.obanana.shop/api/v1/orders/customer/${customerId}`) // .then(response => response.json()) // .then(orderData => { // if (orderData && orderData !== "") { // console.log(orderData) // const filteredOrders = orderData.filter(order => order.status.toUpperCase() === 'CART'); // const totalAmountSum = filteredOrders.reduce((sum, order) => { // const totalAmount = parseFloat(order.total_amount); // return sum + totalAmount; // }, 0); // console.log('Total Amount Sum:', totalAmountSum); // document.getElementById(`floatCartTotalAmount`).innerText = totalAmountSum; // } else { // alert('Error fetching order data'); // } // }) // .catch(error => console.error('Error:', error)); // } // function updateOrder(orderId, existingItemId) { // var updateOrderXhr = new XMLHttpRequest(); // // const token = ''; // updateOrderXhr.open("PUT", `https://api.obanana.shop/api/v1/orders/${orderId}/items/${existingItemId}`, true); // updateOrderXhr.setRequestHeader("Content-Type", "application/json"); // updateOrderXhr.setRequestHeader("Authorization", "Bearer " + token); // updateOrderXhr.onreadystatechange = function() { // if (updateOrderXhr.readyState === 4) { // if (updateOrderXhr.status === 200) { // var response = JSON.parse(updateOrderXhr.responseText); // console.log("Order updated:", response); // var cartItem = document.getElementById(`order_${response._id}`); // if (cartItem) { // var updatedQuantity = response.items[0].quantity; // Use the correct quantity from the updated order // var totalAmount = response.items[0].price * updatedQuantity; // // If the cart item already exists, update its content using innerHTML // cartItem.innerHTML = ` // // product // //
// ${response.items[0].product.name} // // Unit Price: ${response.items[0].price} // // Subtotal: ${totalAmount} //
//
-
// //
+
//
// x //
// `; // document.getElementById(`qty-input-${response.items[0]._id}`).value = updatedQuantity; // } else { // // If the cart item doesn't exist, create a new one // console.log("Error updating order:", updateOrderXhr.responseText); // } // getLatestOrders(); // updateCartItemCount(); // } else { // // Handle error response from the server // console.log("Error response from the server"); // console.log(xhr.responseText); // Log the server's response // } // } // }; // var existingQuantity = parseInt(existingOrder.items[0].quantity, 10); // var newQuantity = parseInt(productQuantity, 10); // var updatedQuantity = existingQuantity + newQuantity; // var updateData = { // quantity: updatedQuantity, // }; // updateOrderXhr.send(JSON.stringify(updateData)); // var patchTotalAmountXhr = new XMLHttpRequest(); // patchTotalAmountXhr.open("PATCH", `https://api.obanana.shop/api/v1/orders/${orderId}`, true); // patchTotalAmountXhr.setRequestHeader("Content-Type", "application/json"); // patchTotalAmountXhr.setRequestHeader("Authorization", "Bearer " + token); // var originalPrice = productPrice; // var totalAmount = originalPrice * updatedQuantity; // console.log(originalPrice); // console.log(totalAmount); // var patchData = { // total_amount: totalAmount // }; // patchTotalAmountXhr.send(JSON.stringify(patchData)); // } // }) // } // function popupWishlist(wishproduct, wishCustomer) { // var productObject = JSON.parse(wishproduct); // var customerObject = JSON.parse(wishCustomer); // var prodId = productObject._id; // var custId = customerObject[0]._id; // fetch('https://api.obanana.shop/api/v1/customers/' + custId) // .then(response => response.json()) // .then(data => { // const existingWishlist = data.favorites ?? { // products: [], // vendors: [] // }; // // Check if the product already exists in the wishlist // const isAlreadyAdded = existingWishlist.products.some(product => product._id === prodId); // if (!isAlreadyAdded) { // const newFavorites = { // products: [{ // ...productObject, // Use the spread operator to include all properties from product_details // }] // }; // existingWishlist.products.push(newFavorites.products[0]); // return fetch('https://api.obanana.shop/api/v1/customers/' + custId, { // method: 'PATCH', // headers: { // 'Content-Type': 'application/json' // }, // body: JSON.stringify({ // favorites: existingWishlist // }), // }); // } else { // console.log("Product already exists in favorites"); // // Optionally, you can notify the user that the product is already in their favorites // // alert("Product already exists in favorites"); // return Promise.resolve(); // Resolve the promise to continue the chain // } // }) // .then(response => { // if (response && response.ok) { // // Handle success (e.g., show a success message) // console.log("Added to favorites") // updateWishItemCount(); // // location.reload(); // } else if (response) { // // Handle error // console.error('Failed to submit data'); // alert('Failed to submit data'); // } // }) // .catch(error => { // // Handle network or other errors // console.error('Error:', error); // alert('Error submitting data'); // }); // } // function deleteOrder(orderId) { // fetch('https://api.obanana.shop/api/v1/orders/' + orderId, { // method: 'DELETE' // }) // .then(response => response.json()) // .then(data => { // if (data && data !== "") { // // Order deleted successfully, update the UI // document.getElementById('order_' + data._id).remove(); // Assuming each order has a unique ID in the DOM // } else { // alert('Error deleting order: ' + data.status); // } // }) // .catch(error => console.error('Error:', error)); // } function login(username, password, callback) { fetch("https://api.obanana.shop/api/v1/login", { method: "POST", headers: { "Content-Type": "application/json", "X-Api-Key": "{{apiKey}}" }, body: JSON.stringify({ username: username, password: password }) }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error("Unable to login"); } }) .then(data => { fetch("update-token-session.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: data.token }) }) .then(response => response.json()) .then(result => { if (result.status === 'success') { sessionToken = data.token; console.log("New Token:", sessionToken); callback(sessionToken); } else { throw new Error("Unable to update session token"); } }); }) .catch(error => { console.error("Error:", error.message); }); } function popupAddToCart(product, productVendor, token, email, password, customer) { // var productObj = JSON.parse(product); // console.log(product) var cleanedProduct = product.replace(/[\r\n]+/gm, ''); var productObj; try { // Attempt to parse 'cleanedProduct' as JSON productObj = JSON.parse(cleanedProduct); // Log the parsed object for debugging console.log("Parsed Product Object:", productObj); } catch (error) { // Log the error and return, or handle it accordingly console.error("Error parsing product JSON: ", error); return; } // Now 'productObj' contains the parsed product or the original object/array try { var trimmedCustomer = customer var customerObj = JSON.parse(trimmedCustomer); console.log("Customer Object: ", customerObj); } catch (error) { console.error("Error parsing customer JSON: ", error); } var vendorObj = JSON.parse(productVendor); var sessionToken = token; var productImage = productObj.product_image; var productId = productObj._id; var productName = productObj.product_name; var productPrice = productObj.sale_price ? productObj.sale_price : productObj.regular_price; var shippingFee = productObj.shipping_fee && productObj.shipping_fee !=="" ? productObj.shipping_fee: '50' ; var productVendorId = vendorObj._id; var vendorName = vendorObj.user_login; var productQuantity = 1; var customerId = customerObj[0]._id; var customerName = customerObj[0].first_name + ' ' + customerObj[0].last_name; console.log("Product email: " + email); console.log("Product password: " + password); console.log("Product Token: " + sessionToken); console.log("Product Image: " + productImage); console.log("Product ID: " + productId); console.log("Product Name: " + productName); console.log("Product Price: " + productPrice); console.log("Product Vendor ID: " + productVendorId); console.log("Product Vendor Name: " + vendorName); console.log("Product Quantity: " + productQuantity); console.log("Customer ID: " + customerId); console.log("Customer Name: " + customerName); login(email, password, function(token){ var productData = { product: { product_image: productImage, product_id: productId, name: productName, }, price: productPrice, quantity: productQuantity, vendor_id: productVendorId, vendor_name: vendorName, }; var totalAmount = productData.price * productData.quantity; var customerData = { customer_id: customerId, name: customerName, }; var existingOrder; var orderCheckXhr = new XMLHttpRequest(); orderCheckXhr.open("GET", "https://api.obanana.shop/api/v1/orders/customer/" + customerData.customer_id, true); orderCheckXhr.onreadystatechange = function() { if (orderCheckXhr.readyState === 4) { if (orderCheckXhr.status === 200) { var orders = JSON.parse(orderCheckXhr.responseText); var existingItemId; var ordersFiltered = orders.filter((e) => e.status === "CART" || e.status === "Cart") console.log() existingOrder = ordersFiltered.find(order => order.items.some(item => item.product.product_id === productData.product.product_id)); console.log("exist? " + existingOrder) if (existingOrder) { var existingItemId = existingOrder.items[0]._id; // If the product is found in an existing CART order, update the order updateOrder(existingOrder._id, existingItemId); } else { // If the product is not found or the order is not a CART, create a new order console.log("No Order Yet!") createNewOrder() } } else if (orderCheckXhr.status === 404) { // If the customer has no orders, create a new order console.log("No Order Yet!") createNewOrder(); } else { // Handle error response from the server when checking orders console.log("Error checking orders:", orderCheckXhr.responseText); } } }; orderCheckXhr.send(); function createNewOrder() { var xhr = new XMLHttpRequest(); // Declare requestData before sending the request var requestData = { items: [productData], customer: [customerData], status: "CART", total_amount: totalAmount, shipping_fee: shippingFee, }; console.log("Request data:", requestData); // Debugging statement // const token = ''; xhr.open("POST", "https://api.obanana.shop/api/v1/orders", true); xhr.setRequestHeader("Content-Type", "application/json", ); xhr.setRequestHeader("Authorization", "Bearer " + token); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 201) { var response = JSON.parse(xhr.responseText); console.log("Response:", response); // Debugging statement // Update the cart dynamically var cartList = document.querySelector(".eccart-pro-items"); var newOrder = document.createElement("li"); newOrder.id = `order_${response._id}`; console.log(response) newOrder.innerHTML = ` product
${response.items[0].product.name} Unit Price: ${response.items[0].price} Subtotal: ${totalAmount}
-
+
`; getLatestOrders() updateCartItemCount() cartList.appendChild(newOrder); } else { // Handle error response from the server console.log("Error response from the server"); console.log(xhr.responseText); // Log the server's response } } }; xhr.send(JSON.stringify(requestData)); } function getLatestOrders() { // var customerId = '' // Fetch the order data fetch(`https://api.obanana.shop/api/v1/orders/customer/${customerId}`) .then(response => response.json()) .then(orderData => { if (orderData && orderData !== "") { console.log(orderData) const filteredOrders = orderData.filter(order => order.status.toUpperCase() === 'CART'); const totalAmountSum = filteredOrders.reduce((sum, order) => { const totalAmount = parseFloat(order.total_amount); return sum + totalAmount; }, 0); console.log('Total Amount Sum:', totalAmountSum); document.getElementById(`floatCartTotalAmount`).innerText = totalAmountSum; } else { alert('Error fetching order data'); } }) .catch(error => console.error('Error:', error)); } function updateOrder(orderId, existingItemId) { var updateOrderXhr = new XMLHttpRequest(); // const token = ''; updateOrderXhr.open("PUT", `https://api.obanana.shop/api/v1/orders/${orderId}/items/${existingItemId}`, true); updateOrderXhr.setRequestHeader("Content-Type", "application/json"); updateOrderXhr.setRequestHeader("Authorization", "Bearer " + token); updateOrderXhr.onreadystatechange = function() { if (updateOrderXhr.readyState === 4) { if (updateOrderXhr.status === 200) { var response = JSON.parse(updateOrderXhr.responseText); console.log("Order updated:", response); var cartItem = document.getElementById(`order_${response._id}`); if (cartItem) { var updatedQuantity = response.items[0].quantity; // Use the correct quantity from the updated order var totalAmount = response.items[0].price * updatedQuantity; // If the cart item already exists, update its content using innerHTML cartItem.innerHTML = ` product
${response.items[0].product.name} Unit Price: ${response.items[0].price} Subtotal: ${totalAmount}
-
+
x
`; document.getElementById(`qty-input-${response.items[0]._id}`).value = updatedQuantity; } else { // If the cart item doesn't exist, create a new one console.log("Error updating order:", updateOrderXhr.responseText); } getLatestOrders(); updateCartItemCount(); } else { // Handle error response from the server console.log("Error response from the server"); console.log(xhr.responseText); // Log the server's response } } }; var existingQuantity = parseInt(existingOrder.items[0].quantity, 10); var newQuantity = parseInt(productQuantity, 10); var updatedQuantity = existingQuantity + newQuantity; var updateData = { quantity: updatedQuantity, }; updateOrderXhr.send(JSON.stringify(updateData)); var patchTotalAmountXhr = new XMLHttpRequest(); patchTotalAmountXhr.open("PATCH", `https://api.obanana.shop/api/v1/orders/${orderId}`, true); patchTotalAmountXhr.setRequestHeader("Content-Type", "application/json"); patchTotalAmountXhr.setRequestHeader("Authorization", "Bearer " + token); var originalPrice = productPrice; var totalAmount = originalPrice * updatedQuantity; console.log(originalPrice); console.log(totalAmount); var patchData = { total_amount: totalAmount }; patchTotalAmountXhr.send(JSON.stringify(patchData)); } }) } function popupWishlist(wishproduct, wishCustomer) { var productObject = JSON.parse(wishproduct); var customerObject = JSON.parse(wishCustomer); var prodId = productObject._id; var custId = customerObject[0]._id; fetch('https://api.obanana.shop/api/v1/customers/' + custId) .then(response => response.json()) .then(data => { const existingWishlist = data.favorites ?? { products: [], vendors: [] }; // Check if the product already exists in the wishlist const isAlreadyAdded = existingWishlist.products.some(product => product._id === prodId); if (!isAlreadyAdded) { const newFavorites = { products: [{ ...productObject, // Use the spread operator to include all properties from product_details }] }; existingWishlist.products.push(newFavorites.products[0]); return fetch('https://api.obanana.shop/api/v1/customers/' + custId, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ favorites: existingWishlist }), }); } else { console.log("Product already exists in favorites"); // Optionally, you can notify the user that the product is already in their favorites // alert("Product already exists in favorites"); return Promise.resolve(); // Resolve the promise to continue the chain } }) .then(response => { if (response && response.ok) { // Handle success (e.g., show a success message) console.log("Added to favorites") updateWishItemCount(); // location.reload(); } else if (response) { // Handle error console.error('Failed to submit data'); alert('Failed to submit data'); } }) .catch(error => { // Handle network or other errors console.error('Error:', error); alert('Error submitting data'); }); }