diff --git a/assets/js/tester11.js b/assets/js/tester11.js index ece88cf..64ae332 100644 --- a/assets/js/tester11.js +++ b/assets/js/tester11.js @@ -403,245 +403,248 @@ // .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); + 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"); } - } catch (error) { - console.error("Error parsing customer JSON: ", error); - } - let vendorData = decodeURIComponent(productVendor); - - 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 productData = { - product: { - product_image: productImage, - product_id: productId, - name: productName, + }) + .then((data) => { + fetch("update-token-session.php", { + method: "POST", + headers: { + "Content-Type": "application/json", }, - 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 + 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 = 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 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 { - // Handle error response from the server when checking orders - console.log("Error checking orders:", orderCheckXhr.responseText); } + } 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, }; - - 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}`; - 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 = ` + + 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 = ` + + @@ -654,80 +657,80 @@ function login(username, password, callback) {
`; - 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 - } + 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 = ` + } + }; + + 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 = ` @@ -744,164 +747,163 @@ function login(username, password, callback) { `; - 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(); + document.getElementById( + `qty-input-${response.items[0]._id}` + ).value = updatedQuantity; } else { - // Handle error response from the server - console.log("Error response from the server"); - console.log(xhr.responseText); // Log the server's response + // If the cart item doesn't exist, create a new one + console.log("Error updating order:", updateOrderXhr.responseText); } - } - }; - 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); - 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; + + 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 } } - - // 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 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)); } - 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", + }); +} + +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 }, - 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"); - }); - } - \ No newline at end of file + ], + }; + + 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"); + }); +} diff --git a/catalog-single-vendor.php b/catalog-single-vendor.php index fe0a7b0..88b4844 100644 --- a/catalog-single-vendor.php +++ b/catalog-single-vendor.php @@ -133,21 +133,35 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate