// 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); let productData = decodeURIComponent(product); console.log(productData); var cleanedProduct = productData.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 { let customerData = decodeURIComponent(customer); var cleanedCustomer = new Array(customerData); try { function parseJSONSafely(jsonString) { try { // First attempt to parse the JSON var parsedJSON = JSON.parse(jsonString); // Second attempt to parse the JSON var parsedJSONAgain = JSON.parse(parsedJSON); // If the second parse succeeds, return its result return parsedJSONAgain; } catch (error) { // If an error occurs during the second parse, return the result of the first parse return parsedJSON; } } // Example usage: var customerObj = parseJSONSafely(cleanedCustomer); console.log(); } catch (error) { console.error("Error parsing customer JSON:", error); } } catch (error) { console.error("Error parsing customer JSON: ", error); } let vendorData = null; console.log(productVendor); if ( productVendor === undefined || productVendor === null || productVendor === "undefined" ) { console.log("here i am"); var vendorCheckXhr = new XMLHttpRequest(); vendorCheckXhr.open( "GET", "https://api.obanana.shop/api/v1/vendors/" + productData.vendor_api_id, true ); vendorCheckXhr.onreadystatechange = function () { if (vendorCheckXhr.readyState === 4) { if (vendorCheckXhr.status === 200) { var vendorObj = JSON.parse(vendorCheckXhr.responseText); console.log(vendorObj); } } }; vendorCheckXhr.send(); } else { vendorData = decodeURIComponent(productVendor); console.log("vendorData"); var vendorObj = JSON.parse(vendorData); } var sessionToken = token; var productImage = productObj.images; 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 Names: " + customerName); login(email, password, function (token) { var priceMatrix = productObj.price_matrix !== "" ? productObj.price_matrix : "[]"; // var quantityValue = productData.quantity; var minimumOrder = productObj.minimum_order; var quantityValue = productObj.minimum_order == "" ? productQuantity : "1"; // var minimumOrder = productObj.minimum_order !=="" ? productObj.minimum_order : '1'; // var quantityValue = minimumOrder ; if (parseInt(quantityValue) < minimumOrder) { quantityValue = minimumOrder; alert("The minimum order quantity is " + minimumOrder); } //Apply Matrix var productPrice; var foundPrice = false; if (priceMatrix.length > 0) { for (var i = 0; i < priceMatrix.length; i++) { for (var j = 0; j < priceMatrix[i].length; j++) { var currentQuantity = parseFloat(priceMatrix[i][j].quantity); var nextQuantity = j < priceMatrix[i].length - 1 ? parseFloat(priceMatrix[i][j + 1].quantity) : Infinity; if ( quantityValue >= currentQuantity && quantityValue < nextQuantity ) { productPrice = parseFloat(priceMatrix[i][j].price); foundPrice = true; break; } } if (foundPrice) { break; } } } if (!foundPrice) { productPrice = productObj.sale_price ? productObj.sale_price : productObj.regular_price; // productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice")); // productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice")); // productPrice; } var productData = { product: { product_image: productImage, product_id: productId, name: productName, }, price: productPrice, quantity: quantityValue, vendor_id: productVendorId, vendor_name: vendorName, }; //Apply Matrix console.log("Product dataa:", productData); var totalAmount = productData.price * productData.quantity; var customerData = { customer_id: customerId, name: customerName, }; console.log("Customer data:", customerData); // console.log("Price Matrix: " + priceMatrix); // Check if the product is already in the order API 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.className = "rowcart"; newOrder.id = `order_${response._id}`; var imageUrl = response.items[0].product.product_image ? response.items[0].product.product_image.split(",")[0].trim() : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; console.log(response); newOrder.innerHTML = ` product
${response.items[0].product.name} Unit Price11: ${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; var imageUrl = response.items[0].product.product_image ? response.items[0].product.product_image.split(",")[0].trim() : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; // 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}
-
+
`; 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(quantityValue, 10); var updatedQuantity = existingQuantity + newQuantity; // Check if the updated quantity exceeds the previous price matrix var newProductPrice = productPrice; var foundNewPrice = false; if (priceMatrix.length > 0) { for (var i = 0; i < priceMatrix.length; i++) { for (var j = 0; j < priceMatrix[i].length; j++) { var currentQuantity = parseFloat(priceMatrix[i][j].quantity); var nextQuantity = j < priceMatrix[i].length - 1 ? parseFloat(priceMatrix[i][j + 1].quantity) : Infinity; if ( updatedQuantity >= currentQuantity && updatedQuantity < nextQuantity ) { newProductPrice = parseFloat(priceMatrix[i][j].price); foundNewPrice = true; break; } } if (foundNewPrice) { break; } } } if (foundNewPrice) { productPrice = newProductPrice; } var updateData = { quantity: updatedQuantity, price: productPrice, }; 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 = productPrice * 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); let productData = decodeURIComponent(wishproduct); console.log(productData); var cleanedProduct = productData.replace(/[\r\n]+/gm, ""); var productObject; try { // Attempt to parse 'cleanedProduct' as JSON productObject = JSON.parse(cleanedProduct); // Log the parsed object for debugging console.log("Parsed Product Object:", productObject); } catch (error) { // Log the error and return, or handle it accordingly console.error("Error parsing product JSON: ", error); return; } // var customerObject = JSON.parse(wishCustomer); try { let customerData = decodeURIComponent(wishCustomer); var cleanedCustomer = new Array(customerData); try { function parseJSONSafely(jsonString) { try { // First attempt to parse the JSON var parsedJSON = JSON.parse(jsonString); // Second attempt to parse the JSON var parsedJSONAgain = JSON.parse(parsedJSON); // If the second parse succeeds, return its result return parsedJSONAgain; } catch (error) { // If an error occurs during the second parse, return the result of the first parse return parsedJSON; } } // Example usage: var customerObject = parseJSONSafely(cleanedCustomer); console.log(); } catch (error) { console.error("Error parsing customer JSON:", error); } } catch (error) { console.error("Error parsing customer JSON: ", error); } 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"); }); }