- new update

This commit is contained in:
mark H 2024-04-30 14:25:28 +08:00
parent 12a5e426b5
commit a9853d178c
11 changed files with 938 additions and 767 deletions

View File

@ -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 = '<?php echo $_SESSION["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 = '<?php echo $_SESSION["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 = `
<input type="checkbox" class="rowcartCheckbox" name="cart-item[]" value="${response._id}"/>
<a href="product-left-sidebar.php?id=${response.items[0]._id}" class="sidekka_pro_img">
<img src="${imageUrl}" alt="product" />
</a>
@ -654,80 +657,80 @@ function login(username, password, callback) {
<!-- 02-16-2024 Stacy added style -->
<div class="qty-plus-minuses" style="display:flex; overflow:visible; align-items:center; padding-top:10px;">
<div class="qty-btn" style="color:#ffaa00; font-size:35px; padding-right:5px; cursor: pointer;" onclick="qtyDecrement('${response._id}', '${response.items[0]._id}', true)">-</div>
<input style="width:100px; height:40px" id="qty-input-${response.items[0]._id}" class="qty-input" type="number" name="ec_qtybtn" value="${productData.quantity}" oninput="handleQtyInput(this, '${response._id}', '${response.items[0]._id}', true)"/>
<input style="width:80px; height:40px" id="qty-input-${response.items[0]._id}" class="qty-input" type="number" name="ec_qtybtn" value="${productData.quantity}" oninput="handleQtyInput(this, '${response._id}', '${response.items[0]._id}', true)"/>
<div class="qty-btn" style="color:#ffaa00; font-size:30px; padding-left:5px; cursor: pointer;" onclick="qtyIncrement('${response._id}', '${response.items[0]._id}', true)">+</div>
<a href="#" class="removeCart" onclick="deleteOrder('${response._id}')"><i class="ecicon eci-trash" style="padding:20px; opacity:70%"></i></a>
<a href="#" style="margin-left:10px;" class="removeCart" onclick="deleteOrder('${response._id}')"><i class="ecicon eci-trash" style="padding:20px; opacity:70%"></i></a>
</div>
<!-- 02-16-2024 Stacy added style -->
</div>
`;
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 = '<?php echo $customer_data[0]['_id'] ?>'
// 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 = '<?php echo $_SESSION["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 = '<?php echo $customer_data[0]['_id'] ?>'
// 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 = '<?php echo $_SESSION["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 = `
<a href="product-left-sidebar.php?id=${response.items[0]._id}"" class="sidekka_pro_img">
<img src="${imageUrl}" alt="product">
</a>
@ -744,164 +747,163 @@ function login(username, password, callback) {
<a href="#" class="removeCart" onclick="deleteOrder('${response._id}')"><i class="ecicon eci-trash" style="padding:20px; opacity:70%"></i></a>
</div>
`;
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");
});
}
],
};
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");
});
}

View File

@ -133,21 +133,35 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
<!-- Background css -->
<link rel="stylesheet" id="bg-switcher-css" href="assets/css/backgrounds/bg-4.css">
<script>
function updateCartItemCount() {
$.get("cartitems.php?id=<?php echo $_SESSION['customerId']; ?>", function(data, status) {
if (data != "") {
console.log("Data: " + data + "\nStatus: " + status);
document.getElementById("cartItemCount").innerHTML = data;
}
});
function updateCartItemCount() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "cartitems.php?id=<?php echo $_SESSION['customerId']; ?>", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
if (data !== "") {
console.log("Data: " + data);
document.getElementById("cartItemCount").innerHTML = data;
}
}
function updateWishItemCount() {
$.get("wishlistitems.php?id=<?php echo $_SESSION['customerId']; ?>", function(data) {
if (data != "") {
document.getElementById("wishItemCount").innerHTML = data;
}
});
};
xhr.send();
}
function updateWishItemCount() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "wishlistitems.php?id=<?php echo $_SESSION['customerId']; ?>", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
if (data !== "") {
document.getElementById("wishItemCount").innerHTML = data;
}
}
};
xhr.send();
}
</script>
<!-- raymart added css feb 14 2024 -->
<style>
@ -302,7 +316,7 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
<div class="ec-page-description ec-page-description-info"style="background: orange;">
<div class="ec-page-block" style="background: #393e46;">
<div class="ec-catalog-vendor">
<a href="vendor-profile.html">
<?php
if (isset($vendor["vendor_image"])) {
?><img loading="lazy" src="<?php echo $vendor["vendor_image"] ?>" alt="vendor img"><?php
@ -310,14 +324,14 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
?><img loading="lazy" src="https://api.obanana.com/images/storage/web_images/1710214273217-no_image.png" alt="vendor img"><?php
}
?>
</a>
</div>
<div class="ec-catalog-vendor-info row" style="justify-content: center;">
<div class="col-lg-3 col-md-6 ec-catalog-name pad-15">
<a href="vendor-profile.html">
<h6 class="name"><?php echo $vendor["user_login"] ?></h6>
</a>
<p>( Retail Business )</p>
</div>
<!-- raymart remove level feb 22 2024 -->
@ -326,18 +340,18 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
<p>Level : 9 out of 10</p>
</div> -->
<div class="col-lg-3 col-md-6 ec-catalog-pro-count pad-15">
<a href="vendor-profile.html">
<h6>Seller Products</h6>
<?php
?>
</a>
<p><?php echo count($products) ?> Products</p>
</div>
<div class="col-lg-3 col-md-6 ec-catalog-since pad-15">
<a href="vendor-profile.html">
<h6>Seller since</h6>
<p><?php echo $vendor["date_registered"] ?></p>
</a>
</div>
</div>
</div>
@ -391,134 +405,8 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
<!-- Shop content Start -->
<div class="shop-pro-content">
<div class="shop-pro-inner">
<div class="row" id="product-container">
<?php
//var_dump($products);
foreach ($filteredProducts as $product){
// $vendorOfProduct = getVendorbyId($product['vendor_api_id']);
?>
<div class="col-lg-4 col-md-6 col-sm-6 col-xs-6 mb-6 pro-gl-content">
<div class="ec-product-inner">
<div class="ec-pro-image-outer" style="max-width: 290px; height: 350px;">
<div class="ec-pro-image">
<!-- raymart added for link for product feb 22 2024 -->
<a class="image" href="product-left-sidebar.php?id=<?php echo $product["_id"] ?>"<?php echo $product["product_image"] ?>>
<!-- raymart replace new function for images of the product march 8 2024 -->
<?php
if (isset($product['images'])) {
$image_urls = explode(',', $product['images']);
if (!empty($image_urls)) {
$first_image_url = trim($image_urls[0]);
?>
<img loading="lazy" class="main-image" src="<?php echo $first_image_url; ?>" alt="edit" style="border: 1px solid #eeeeee; height: 330px; object-fit: cover;"/>
<?php
}
} else {
?>
<img loading="lazy" class="main-image" src="https://api.obanana.com/images/storage/web_images/1710214273217-no_image.png" alt="edit" />
<?php
}
?>
</a>
<!-- raymart edit action feb 14 2024 -->
<div class="ec-pro-actions" style="bottom: -36px;">
<!-- raymart replace updated prize for the product march 8 2024 -->
<?php if (isset($product["sale_price"]) && $product["sale_price"] > 0) : ?>
<button title="Add To Cart" onclick="popupAddToCart(`<?php echo htmlspecialchars(json_encode($product), ENT_QUOTES, 'UTF-8'); ?>`,`<?php echo htmlspecialchars($vendorOfProduct, ENT_QUOTES, 'UTF-8'); ?>`, `<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>` , `<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>` , `<?php echo isset($_SESSION['password']) ? $_SESSION['password'] : ''; ?>` , `<?php echo htmlspecialchars(json_encode($customer_data), ENT_QUOTES, 'UTF-8'); ?>`);" class="add-to-cart"><i class="fi-rr-shopping-basket"></i> Add To Cart</button>
<a class="ec-btn-group wishlist" title="Wishlist" onclick="popupWishlist('<?php echo htmlspecialchars(json_encode($product), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(json_encode($customer_data), ENT_QUOTES, 'UTF-8'); ?>');"><i class="fi-rr-heart"></i></a>
<?php elseif (isset($product["regular_price"]) && $product["regular_price"] != "") : ?>
<button title="Add To Cart" onclick="popupAddToCart(`<?php echo htmlspecialchars(json_encode($product), ENT_QUOTES, 'UTF-8'); ?>`,`<?php echo htmlspecialchars($vendorOfProduct, ENT_QUOTES, 'UTF-8'); ?>`, `<?php echo isset($_SESSION['token']) ? $_SESSION['token'] : ''; ?>` , `<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>` , `<?php echo isset($_SESSION['password']) ? $_SESSION['password'] : ''; ?>` , `<?php echo htmlspecialchars(json_encode($customer_data), ENT_QUOTES, 'UTF-8'); ?>`);" class="add-to-cart"><i class="fi-rr-shopping-basket"></i> Add To Cart</button>
<a class="ec-btn-group wishlist" title="Wishlist" onclick="popupWishlist('<?php echo htmlspecialchars(json_encode($product), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(json_encode($customer_data), ENT_QUOTES, 'UTF-8'); ?>');"><i class="fi-rr-heart"></i></a>
<?php else : ($product["regular_price"] == "" || $product["regular_price"] == null) ?>
<a class="ec-btn-group wishlist" title="Wishlist" onclick="popupWishlist('<?php echo htmlspecialchars(json_encode($product), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(json_encode($customer_data), ENT_QUOTES, 'UTF-8'); ?>');"><i class="fi-rr-heart"></i></a>
<?php endif; ?>
</div>
<!-- <span class="percentage">20%</span>
<a href="#" class="quickview" data-link-action="quickview" title="Quick view" data-bs-toggle="modal" data-bs-target="#ec_quickview_modal"><i class="fi-rr-eye"></i></a>
<div class="ec-pro-actions">
<a href="compare.html" class="ec-btn-group compare" title="Compare"><i class="fi fi-rr-arrows-repeat"></i></a>
<button title="Add To Cart" class="add-to-cart"><i class="fi-rr-shopping-basket"></i> Add To Cart</button>
<a class="ec-btn-group wishlist" title="Wishlist"><i class="fi-rr-heart"></i></a>
</div> -->
</div>
</div>
<div class="ec-pro-content">
<h5 class="ec-pro-title"><a href="product-left-sidebar.php?id=<?php echo $product["_id"] ?>" style="width: 90%; text-wrap: wrap;"><?php echo $product["product_name"] ?></a></h5>
<!-- raymart remove ratings feb 22 2024 -->
<!-- <div class="ec-pro-rating">
<i class="ecicon eci-star fill"></i>
<i class="ecicon eci-star fill"></i>
<i class="ecicon eci-star fill"></i>
<i class="ecicon eci-star fill"></i>
<i class="ecicon eci-star"></i>
</div> -->
<!-- <div class="ec-pro-list-desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dutmmy text ever since the 1500s, when an unknown printer took a galley.</div> -->
<span class="ec-price">
<!-- raymart added $ to pesos function feb 22 2024 -->
<?php if (isset($product["sale_price"]) && $product["sale_price"] > 0) : ?>
<span class="old-price">&#8369;<?php echo number_format($product["regular_price"], 2, ".", ",") ?></span>
<span class="new-price">&#8369;<?php echo number_format($product["sale_price"], 2, ".", ",") ?></span>
<?php elseif (isset($product["regular_price"]) && $product["regular_price"] != "") : ?>
<span class="new-price">&#8369;<?php echo number_format($product["regular_price"], 2, ".", ",") ?></span>
<?php elseif ($product["regular_price"] == "" || $product["regular_price"] == null) : ?>
<span class="inquire-text">Inquire</span>
<?php else : ?>
<span class="inquire-text">Inquire</span>
<?php endif; ?>
<!-- <?php if (isset($product["sale_price"]) && $product["sale_price"] > 0) : ?>
<span class="old-price">&#8369;<?php echo number_format($product["regular_price"], 2, ".", ",") ?></span>
<span class="new-price">&#8369;<?php echo number_format($product["sale_price"], 2, ".", ",") ?></span>
<?php elseif (isset($product["regular_price"]) && $product["regular_price"] != "") : ?>
<span class="new-price">&#8369;<?php echo number_format($product["regular_price"], 2, ".", ",") ?></span>
<?php elseif ($product["regular_price"] == "" || $product["regular_price"] == null) : ?>
<span class="inquire-text">Inquire</span>
<?php else : ?>
<span class="inquire-text">Inquire</span>
<?php endif; ?> -->
</span>
<div class="ec-pro-option">
<!-- raymart remove color and size function feb 22 2024 -->
<!-- <div class="ec-pro-color">
<span class="ec-pro-opt-label">Color</span>
<ul class="ec-opt-swatch ec-change-img">
<?php
if (isset($product["product_image"]) && $product["product_image"] <> "") {
?>
<li class="active"><a href="#" class="ec-opt-clr-img" data-src="<?php echo $product["product_image"] ?>" data-src-hover="<?php echo $product["product_image"] ?>" data-tooltip="Gray"><span style="background-color:#e8c2ff;"></span></a></li>
<li><a href="#" class="ec-opt-clr-img" data-src="<?php echo $product["product_image"] ?>" data-src-hover="<?php echo $product["product_image"] ?>" data-tooltip="Orange"><span style="background-color:#9cfdd5;"></span></a></li>
<?php
} else {
?>
<li class="active"><a href="#" class="ec-opt-clr-img" data-src="assets/images/product-image/6_1.jpg" data-src-hover="assets/images/product-image/6_1.jpg" data-tooltip="Gray"><span style="background-color:#e8c2ff;"></span></a></li>
<li><a href="#" class="ec-opt-clr-img" data-src="assets/images/product-image/6_2.jpg" data-src-hover="assets/images/product-image/6_2.jpg" data-tooltip="Orange"><span style="background-color:#9cfdd5;"></span></a></li>
<?php
}
?>
</ul>
</div> -->
<!-- <div class="ec-pro-size">
<span class="ec-pro-opt-label">Size</span>
<ul class="ec-opt-size">
<li class="active"><a href="#" class="ec-opt-sz" data-old="$25.00" data-new="$20.00" data-tooltip="Small">S</a></li>
<li><a href="#" class="ec-opt-sz" data-old="$27.00" data-new="$22.00" data-tooltip="Medium">M</a></li>
<li><a href="#" class="ec-opt-sz" data-old="$30.00" data-new="$25.00" data-tooltip="Large">X</a></li>
<li><a href="#" class="ec-opt-sz" data-old="$35.00" data-new="$30.00" data-tooltip="Extra Large">XL</a></li>
</ul>
</div> -->
</div>
</div>
</div>
</div>
<?php
}
?>
<div class="row" id="product-container3">
</div>
</div>
@ -542,8 +430,10 @@ if (!empty($_GET['minPrice']) || !empty($_GET['maxPrice']) || !empty($_GET['cate
// JavaScript
document.addEventListener("DOMContentLoaded", function() {
loadProducts();
console.log('<?php echo $json ?>')
function loadProducts(page,isFilter) {
let xhrVendors1 = new XMLHttpRequest();
// Define the endpoint URL for fetching vendors
@ -559,67 +449,71 @@ xhrVendors1.onreadystatechange = function() {
var checkedCategories = getCheckedCheckboxes();
var prices = getMinMaxPrices();
function filterFunction(checkedCategories, minPrice, maxPrice,products) {
var filteredProducts = [];
// Filter by category
if (checkedCategories.length > 0) {
let filteredProduct= products?.filter((product) => {
let categoryF = product?.product_category?.toLowerCase();
// console.log('Category (lowercase):', categoryF);
let result =checkedCategories.includes(categoryF)
// console.log('Checked Categories:', result);
return result; // Return a boolean value indicating whether the category is included
});
filteredProducts=filteredProduct
console.log(filteredProducts);
function filterFunction(checkedCategories, minPrice, maxPrice,products) {
var filteredProducts = [];
// Filter by category
if (checkedCategories.length > 0) {
let filteredProduct= products?.filter((product) => {
let categoryF = product?.product_category?.toLowerCase();
// console.log('Category (lowercase):', categoryF);
let result =checkedCategories.includes(categoryF)
// console.log('Checked Categories:', result);
return result; // Return a boolean value indicating whether the category is included
});
filteredProducts=filteredProduct
console.log(filteredProducts);
} else {
// If no categories are selected, keep all products
filteredProducts = products;
}
} else {
// If no categories are selected, keep all products
filteredProducts = products;
}
// If minPrice or maxPrice is not provided, set them to default values
minPriceFinal = minPrice !== '' ? parseInt(minPrice) : 0;
maxPriceFinal = maxPrice !== '' ? parseInt(maxPrice) : Number.MAX_VALUE;
console.log(checkedCategories, minPrice,products)
// If minPrice or maxPrice is not provided, set them to default values
minPriceFinal = minPrice !== '' ? parseInt(minPrice) : 0;
maxPriceFinal = maxPrice !== '' ? parseInt(maxPrice) : Number.MAX_VALUE;
console.log(checkedCategories, minPrice,products)
// Filter by price range
// Filter by price range
if( minPrice !== ''||maxPrice !== ''){
// Filter by price range
// Filter by price range
if( minPrice !== ''||maxPrice !== ''){
filteredProducts = filteredProducts.filter(function(product) {
// Check if product has a sale price
var salePrice = parseInt(product.sale_price);
var regularPrice = parseInt(product.regular_price);
filteredProducts = filteredProducts.filter(function(product) {
// Check if product has a sale price
var salePrice = parseInt(product.sale_price);
var regularPrice = parseInt(product.regular_price);
// Check if salePrice and regularPrice are valid numbers
// if (isNaN(salePrice) || isNaN(regularPrice)) {
// // One of the prices is not a valid number, use 0 instead
// salePrice = salePrice || 0;
// regularPrice = regularPrice || 0;
// }
var priceToCheck = salePrice > 0 ? salePrice : regularPrice;
// console.log(priceToCheck);
return priceToCheck >= minPriceFinal && priceToCheck <= maxPriceFinal;
});
}
console.log({results:filteredProducts});
// Check if salePrice and regularPrice are valid numbers
// if (isNaN(salePrice) || isNaN(regularPrice)) {
// // One of the prices is not a valid number, use 0 instead
// salePrice = salePrice || 0;
// regularPrice = regularPrice || 0;
// }
var priceToCheck = salePrice > 0 ? salePrice : regularPrice;
// console.log(priceToCheck);
return priceToCheck >= minPriceFinal && priceToCheck <= maxPriceFinal;
});
}
console.log({results:filteredProducts});
// Final filtered products
// console.log({results:filteredProducts});
let final = filteredProducts ??[]
return final;
}
let productContainer = document.getElementById("product-container");
// Final filtered products
// console.log({results:filteredProducts});
let final = filteredProducts ??[]
return final;
}
let productContainer = document.getElementById("product-container3");
productContainer.innerHTML = "";
let productsFinal = JSON.parse(xhrVendors1.responseText);
console.log(productsFinal);
// console.log(productsFinal);
productsFinal= filterFunction(checkedCategories, prices.minPrice, prices.maxPrice,productsFinal);
productsFinal?.forEach(function(prod) {
let product = prod;
let vendorOfProduct = prod.vendor_api_id;
let vendorOfProduct = '<?php echo $json ?>';
// let card = document.createElement("div");
let token ="<?php echo $_SESSION['token'] ?>";
let email ="<?php echo $_SESSION['email'] ?>";
@ -636,13 +530,15 @@ let productContainer = document.getElementById("product-container");
img.setAttribute("class", "main-image");
img.setAttribute("src", firstImageUrl);
img.setAttribute("alt", "Product");
img.setAttribute("loading", "lazy");
img.className = "main-image";
imageContainer.appendChild(img);
} else {
let img = document.createElement("img");
img.className = "main-image";
img.setAttribute("style", "width: 290px; height: 200px; object-fit: cover;");
img.setAttribute("loading", "lazy");
img.setAttribute("class", "main-image");
img.setAttribute("src", "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png");
img.setAttribute("alt", "Product");

View File

@ -17,7 +17,21 @@ if ($_SESSION["userId"] <> "") {
$order_ids = [];
if ($cartItems) {
$cartencode = json_encode($cartItems);
if(!empty($_GET['selected'])){
$selectedIds = explode('-', $_GET['selected']);
// Filter $cartItems array based on selected ids
$filteredCartItems = array_filter($cartItems, function($item) use ($selectedIds) {
return in_array($item['_id'], $selectedIds);
});
$cartItems = $filteredCartItems;
$cartencode = json_encode($filteredCartItems);
}else{
$cartItems = $filteredCartItems;
$cartencode = json_encode($cartItems);
}
foreach ($cartItems as $item) {
array_push($order_ids, $item['_id']);
}

View File

@ -1,5 +1,8 @@
<!-- 02-14-2024 Stacy created this file and added contact-us-action.php -->
<?php session_start()?>
<?php
include "functions.php";
session_start()
?>
<!DOCTYPE html>
<html lang="en">

View File

@ -403,6 +403,20 @@ if ($_SESSION["userId"] <> "") {
<span class="cart_title">My Cart</span>
<button class="ec-close">×</button>
</div>
<style>
.rowcart{
display:flex;
justify-content:center;
align-self: center;
flex-direction:row;
}
.rowcartCheckbox{
height:15px;
width:15px;
margin-right:5px;
}
</style>
<ul class="eccart-pro-items">
<?php
//var_dump($order_data[0]['items'][0]['product']);
@ -413,7 +427,8 @@ if ($_SESSION["userId"] <> "") {
$product = getProduct($order['items'][0]['product']['product_id']);
$product_data = json_decode($product, true);
?>
<li id="order_<?php echo $order['_id'] ?>">
<li class="rowcart" id="order_<?php echo $order['_id'] ?>">
<input type="checkbox" class="rowcartCheckbox" name="cart-item[]" value="<?php echo $order['_id']?>"/>
<a href="product-left-sidebar.php?id=<?php echo $order['items'][0]['product']['product_id']; ?>" class="sidekka_pro_img">
<?php
if (isset($order['items'][0]['product']['product_image'])) {
@ -445,7 +460,7 @@ if ($_SESSION["userId"] <> "") {
<div class="qty-btn" style="color:#ffaa00; font-size:35px; margin-right:5px; cursor: pointer;" onclick="qtyDecrement('<?php echo $order['_id']; ?>' ,
'<?php echo $order['items'][0]['_id']; ?>')" onmouseover="this.style.color='#a15d00'" onmouseout="this.style.color='#ffaa00'">-
</div>
<input style="width:100px; height:40px" id="qty-input-<?php echo $order['items'][0]['_id']; ?>" class="qty-input" type="number"
<input style="width:80px; height:40px" id="qty-input-<?php echo $order['items'][0]['_id']; ?>" class="qty-input" type="number"
name="ec_qtybtn" value="<?php echo $order['items'][0]['quantity']; ?>" oninput="handleQtyInput(this, '<?php echo $order['_id']; ?>',
'<?php echo $order['items'][0]['_id']; ?>')" />
<div class="qty-btn" style="color:#ffaa00; font-size:30px; margin-left:5px; cursor: pointer;" onclick="qtyIncrement('<?php echo $order['_id']; ?>' ,
@ -453,7 +468,7 @@ if ($_SESSION["userId"] <> "") {
</div>
<!-- <a class="remove">x</a> -->
<!-- <a href="#" class="removeCart" onclick="deleteOrder('<?php #echo $order['_id']; ?>')">x</a> -->
<a href="#" class="removeCart" style="margin-left:30px;" onclick="deleteOrder('<?php echo $order['_id']; ?>')">
<a href="#" class="removeCart" style="margin-left:10px;" onclick="deleteOrder('<?php echo $order['_id']; ?>')">
<i class="ecicon eci-trash" style="color:#7e7e7e;" onmouseover="this.style.color='#aaaaaa'"
onmouseout="this.style.color='#7e7e7e'"></i>
</a>
@ -522,7 +537,43 @@ if ($_SESSION["userId"] <> "") {
}
let myLatestOrders = [];
var checkboxes = document.querySelectorAll('input[name="cart-item[]"]');
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
getCheckedCheckboxes();
getLatestOrders();
// update_Total()
});
});
function getCheckedCheckboxes() {
var checkboxes = document.querySelectorAll('input[name="cart-item[]"]:checked');
var values = [];
checkboxes.forEach(function(checkbox) {
values.push(checkbox.value.toLowerCase().trim());
});
console.log(values);
return values;
}
function update_Total(){
console.log(orderData);
var checkedCategories = getCheckedCheckboxes();
if (orderData && orderData !== "") {
// Calculate the new total amount based on the updated quantities
const orderInitial= null
if(checkedCategories?.length>0){
orderInitial = orderData?.filter(order => checkedCategories?.includes(order._id));
}else{
orderInitial = orderData
}
let newTotalAmount = orderData.items.reduce((total, item) => {
return total + (item.quantity * item.price);
}, 0);
console.log(response);
}
}
function handleQtyInput(input, orderId, itemId, isFloat) {
login(email, password, function(token) {
var newQuantity = parseInt(input.value);
@ -717,7 +768,18 @@ if ($_SESSION["userId"] <> "") {
if (orderData && orderData !== "") {
console.log(orderData)
const filteredOrders = orderData.filter(order => order.status.toUpperCase() === 'CART');
const totalAmountSum = filteredOrders.reduce((sum, order) => {
var checkedCategories = getCheckedCheckboxes();
let orderInitial= null;
if (filteredOrders && filteredOrders !== "") {
// Calculate the new total amount based on the updated quantities
if(checkedCategories?.length>0){
orderInitial = filteredOrders?.filter(order => checkedCategories?.includes(order._id));
}else{
orderInitial = filteredOrders
}
}
const totalAmountSum = orderInitial.reduce((sum, order) => {
const totalAmount = parseFloat(order.total_amount);
return sum + totalAmount;
}, 0);
@ -752,9 +814,12 @@ if ($_SESSION["userId"] <> "") {
function handleCheckoutButton(event) {
event.preventDefault();
var checkedCategories = getCheckedCheckboxes();
const selectedIdString = checkedCategories.join('-');
login(email, password, function(token) {
window.location.href = "checkouttest.php";
window.location.href = `checkouttest.php?selected=${selectedIdString}`;
});
}

View File

@ -336,6 +336,8 @@ function loadProducts(page,isFilter) {
let img = document.createElement("img");
img.setAttribute("style", "width: 290px; height: 200px; object-fit: cover;");
img.setAttribute("class", "main-image");
img.setAttribute("loading", "lazy");
img.setAttribute("src", firstImageUrl);
img.setAttribute("alt", "Product");
img.className = "main-image";
@ -344,7 +346,7 @@ function loadProducts(page,isFilter) {
let img = document.createElement("img");
img.className = "main-image";
img.setAttribute("style", "width: 290px; height: 200px; object-fit: cover;");
img.setAttribute("loading", "lazy");
img.setAttribute("class", "main-image");
img.setAttribute("src", "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png");
img.setAttribute("alt", "Product");

View File

@ -516,6 +516,8 @@ function loadProducts(page,isFilter) {
img.setAttribute("style", "width: 290px; height: 200px; object-fit: cover;");
img.setAttribute("class", "main-image");
img.setAttribute("src", firstImageUrl);
img.setAttribute("loading", "lazy");
img.setAttribute("alt", "Product");
img.className = "main-image";
imageContainer.appendChild(img);
@ -523,6 +525,7 @@ function loadProducts(page,isFilter) {
let img = document.createElement("img");
img.className = "main-image";
img.setAttribute("style", "width: 290px; height: 200px; object-fit: cover;");
img.setAttribute("loading", "lazy");
img.setAttribute("class", "main-image");
img.setAttribute("src", "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png");
@ -557,7 +560,7 @@ function loadProducts(page,isFilter) {
`<span class="new-price">&#8369;${product?.regular_price}</span>`: 'inquire'
}
</span>
<h6 class="" style="color:#ddd3 !important; font-size:13px; padding-top:10px; padding-bottom:10px"><a href="product-left-sidebar.php?id=${vendor._id}" style="width: 90%; text-wrap: wrap;"> <img style="width:25px; height:25px; border-radius:60px; border: 1px solid #eeee" src="${vendor.vendor_image ?? "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"}" /> ${vendor.user_login}</a></h5>
<h6 class="" style="color:#ddd3 !important; font-size:13px; padding-top:10px; padding-bottom:10px"><a href="catalog-single-vendor.php?id=${vendor._id}" style="width: 90%; text-wrap: wrap;"> <img style="width:25px; height:25px; border-radius:60px; border: 1px solid #eeee" src="${vendor.vendor_image ?? "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"}" /> ${vendor.user_login}</a></h5>
</div>
</div>`;

View File

@ -361,7 +361,22 @@ if ($_SESSION["isVendor"] == true) {
$jsonorder = json_encode($order);
?>
<tr class="tableView" data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<td><img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product"></td>
<td>
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
?>
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
}
else {
?>
<img loading="lazy" class="prod-img" src="<?php echo "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; ?>" alt="product">
<?php
}
?>
</td>
<td><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?></span></td>
<td><span><?php echo $order['items'][0]['quantity']; ?></span></td>
<td><span><?php echo $order['items'][0]['price']; ?></span></td>
@ -436,7 +451,22 @@ if ($_SESSION["isVendor"] == true) {
$jsonorder = json_encode($order);
?>
<tr class="tableView" data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<td><img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product"></td>
<td>
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
?>
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
}
else {
?>
<img loading="lazy" class="prod-img" src="<?php echo "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; ?>" alt="product">
<?php
}
?>
</td>
<td><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?></span></td>
<td><span><?php echo $order['items'][0]['quantity']; ?></span></td>
<td><span><?php echo $order['items'][0]['price']; ?></span></td>
@ -507,7 +537,22 @@ if ($_SESSION["isVendor"] == true) {
$jsonorder = json_encode($order);
?>
<tr class="tableView" data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<td><img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product"></td>
<td>
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
?>
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
}
else {
?>
<img loading="lazy" class="prod-img" src="<?php echo "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; ?>" alt="product">
<?php
}
?>
</td>
<td><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?></span></td>
<td><span><?php echo $order['items'][0]['quantity']; ?></span></td>
<td><span><?php echo $order['items'][0]['price']; ?></span></td>
@ -578,7 +623,20 @@ if ($_SESSION["isVendor"] == true) {
?>
<tr class="tableView">
<td data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
?>
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
}
else {
?>
<img loading="lazy" class="prod-img" src="<?php echo "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; ?>" alt="product">
<?php
}
?>
</td>
<td data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails"><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?></span></td>
<td data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails"><span><?php echo $order['items'][0]['quantity']; ?></span></td>
@ -642,7 +700,7 @@ if ($_SESSION["isVendor"] == true) {
$orders = getOrderbyCustomerId($customer['_id']);
$totalAmount = 0;
$orderExist = false;
if ($orders) {
if ($orders) {
$order_data = json_decode($orders, true);
$_SESSION['cart_items'] = $order_data;
foreach ($order_data as $order) {
@ -656,8 +714,24 @@ if ($_SESSION["isVendor"] == true) {
$jsonorder = json_encode($order);
?>
<tr class="tableView" data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<td><img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product"></td>
<td><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?></span></td>
<td>
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
?>
<img loading="lazy" class="prod-img" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="product">
<?php
}
else {
?>
<img loading="lazy" class="prod-img" src="<?php echo "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; ?>" alt="product">
<?php
}
?>
</td>
<td><span class="text-truncate"><?php echo $order['items'][0]['product']['name']; ?> </span></td>
<td><span><?php echo $order['items'][0]['quantity']; ?></span></td>
<td><span><?php echo $order['items'][0]['price']; ?></span></td>
<td><span><?php echo $order['total_amount'] ?></span></td>

View File

@ -65,7 +65,9 @@ $products = productList();
<!-- Background css -->
<link rel="stylesheet" id="bg-switcher-css" href="assets/css/backgrounds/bg-4.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdn.metroui.org.ua/current/metro.css">
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<style>
.pagination {
display: flex;
@ -186,16 +188,28 @@ $products = productList();
</div>
<div class="ec-vendor-card-body">
<div class="ec-vendor-card-table">
<table class="table ec-table">
<table class="table ec-table"
id="order-table"
data-role="table"
data-pagination="true"
data-searching="true"
data-filtering="true"
data-sorting="true"
data-show-rows-steps="5,10,20,-1"
data-horizontal-scroll="true"
data-rownum="true"
data-table-info-title="Display from $1 to $2 of $3 product(s)"
>
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">Regular Price</th>
<th scope="col">Sale Price</th>
<th scope="col">Minimum Order</th>
<th scope="col">Stock</th>
<th scope="col">Action</th>
<th data-sortable="false" scope="col">Image</th>
<th data-sortable="true" scope="col">Name</th>
<th data-sortable="true" scope="col">Regular Price</th>
<th data-sortable="true" scope="col">Sale Price</th>
<th data-sortable="true" scope="col">Minimum Order</th>
<th data-sortable="true" scope="col">Stock</th>
<th data-sortable="true" scope="col" style=" flex-direction:row; width:200px">Action</th>
</tr>
@ -245,19 +259,22 @@ $products = productList();
</td>
<td><span style="margin-top:8px;"><?php echo $product['product_name']; ?></span></td>
<td><span style="margin-top:8px;"><?php echo $product['regular_price']; ?></span></td>
<td><span style="margin-top:8px;"><?php echo $product['sale_price']; ?></span></td>
<td><span style="margin-top:8px;"><?php echo $product['minimum_order']; ?></span></td>
<td><span style="margin-top:8px;"><?php echo $product['stock']; ?></span></td>
<td style="display:flex; justify-content:space-around;">
<span style="margin-top:4px;">
<input type="checkbox" name="product_checkbox[]" style="width:20px; height:33px; " value="<?php echo $product['_id']; ?>">
</span>
<span style="margin-top:4px;" onclick="editProduct('<?php echo $product['_id'] ?>');">
<a class="mdi mdi-circle-edit-outline" style="font-size:20px;"></a>
</span>
<span style="margin-top:4px;" onclick="deleteProduct('<?php echo $product['_id'] ?>');">
<a class="mdi mdi mdi-delete-outline" style="font-size:20px;"></a>
</span>
<td><span style="margin-top:8px;"><?php echo !empty($product['sale_price']) ?$product['sale_price']: "N/A"; ?></span></td>
<td><span style="margin-top:8px;"><?php echo !empty($product['minimum_order']) ?$product['minimum_order']: "N/A"; ?></span></td>
<td><span style="margin-top:8px;"><?php echo !empty($product['stock']) ?$product['stock']: "N/A"; ?></span></td>
<td >
<div style="display:flex; flex-direction:row; min-width:100px; flex-wrap:nowrap">
<span style="margin-right: 10px;margin-top:4px; color:blue" onclick="editProduct('<?php echo $product['_id'] ?>');">
<a class="mdi mdi-circle-edit-outline" style="font-size:20px; color:blue"></a>
</span>
<span style="margin-top:4px; margin-right: 10px;color:red" onclick="deleteProduct('<?php echo $product['_id'] ?>');">
<a class="mdi mdi mdi-delete-outline" style="font-size:20px; color:red"></a>
</span>
<span style="margin-top:4px; margin-right: 10px;">
<input type="checkbox" name="product_checkbox[]" style="width:20px; height:33px; " value="<?php echo $product['_id']; ?>">
</span>
</div>
</td>
</tr>
<?php
@ -268,13 +285,13 @@ $products = productList();
</div>
</div>
<!-- 03-11-2024 Stacy added pagination -->
<div class="pagination mt-3">
<!-- <div class="pagination mt-3">
<?php
for ($p = 1; $p <= $totalPages; $p++) {
echo "<a href='?page=$p' class='" . ($currentpage == $p ? 'active' : '') . "'>$p</a>";
}
// for ($p = 1; $p <= $totalPages; $p++) {
// echo "<a style='margin-bottom:10px' href='?page=$p' class='" . ($currentpage == $p ? 'active' : '') . "'>$p</a>";
// }
?>
</div>
</div> -->
</div>
</div>
@ -665,6 +682,7 @@ $products = productList();
<script src="assets/js/vendor/jquery.magnific-popup.min.js"></script>
<script src="assets/js/plugins/chart.min.js"></script>
<script src="assets/js/plugins/jquery.sticky-sidebar.js"></script>
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<!-- Main Js -->
<script src="assets/js/chart-main.js"></script>

View File

@ -70,14 +70,14 @@ if ($_SESSION["isCustomer"] == true) {
<link rel="stylesheet" href="assets/css/plugins/countdownTimer.css" />
<link rel="stylesheet" href="assets/css/plugins/slick.min.css" />
<link rel="stylesheet" href="assets/css/plugins/bootstrap.css" />
<link rel="stylesheet" href="https://cdn.metroui.org.ua/current/metro.css">
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<!-- Main Style -->
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/responsive.css" />
<!-- Background css -->
<link rel="stylesheet" id="bg-switcher-css" href="assets/css/backgrounds/bg-4.css">
<style>
#pagination {
display: flex;
@ -222,19 +222,30 @@ if ($_SESSION["isCustomer"] == true) {
</div>
</div>
<div class="ec-vendor-card-body">
<div class="ec-vendor-card-table">
<table class="table ec-table">
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Customer Shipping Address</th>
<th scope="col">Total</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="orderItemsBody">
<div class="table-container" >
<table class="table striped hovered" id="order-table" style="overflow-x: auto;"
data-role="table"
data-pagination="true"
data-searching="true"
data-filtering="true"
data-sorting="true"
data-show-rows-steps="5,10,20,-1"
data-horizontal-scroll="true"
data-rownum="true"
data-table-info-title="Display from $1 to $2 of $3 order(s)"
>
<thead>
<tr>
<th data-sortable="false">Image</th>
<th data-sortable="true">Name</th>
<th data-sortable="true">Status</th>
<th data-sortable="true">Customer</th>
<th data-sortable="true" >Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="orderItemsBody">
<?php
$totalOrders = count($vendorOrders);
$displayLimit = 5;
@ -253,27 +264,66 @@ if ($_SESSION["isCustomer"] == true) {
# 03-11-2024 Stacy modified
if (isset($orderItems['items'][0]['product']['product_image'])) {
?>
<img loading="lazy" class="prod-img" src="<?php echo $orderItems['items'][0]['product']['product_image']; ?>" alt="edit" />
<img loading="lazy" style="height:50px; width:50px" class="prod-img" src="<?php echo $orderItems['items'][0]['product']['product_image']; ?>" alt="edit" />
<?php
} else {
?>
<img loading="lazy" class="prod-img rounded-circle" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/495px-No-Image-Placeholder.svg.png?20200912122019" alt="edit" />
<img loading="lazy" style="height:50px; width:50px" class="prod-img rounded-circle" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/495px-No-Image-Placeholder.svg.png?20200912122019" alt="edit" />
<?php
}
?>
<!-- <?php
if (isset($item['product']['product_image']) && !empty($item['product']['product_image'])) {
echo '<img loading="lazy" src="' . $item['product']['product_image'] . '" alt="Product Image" class="prod-img">';
echo '<img loading="lazy " style="height:50px; width:50px" src="' . $item['product']['product_image'] . '" alt="Product Image" class="prod-img">';
} else {
echo '<img loading="lazy" src="assets/img/vendor/u1.jpg" class="prod-img rounded-circle" alt="Placeholder Image">';
echo '<img loading="lazy " style="height:50px; width:50px" src="assets/img/vendor/u1.jpg" class="prod-img rounded-circle" alt="Placeholder Image">';
}
?> -->
</td>
<td style="max-width:300px;"><span class="text-truncate"><?php echo $item['product']['name']; ?></span></td>
<td><span><?php echo $orderItems['status']; ?></span></td>
<td><span><?php echo $orderItems['shipping_address']['shipping_first_name']; ?></span></td>
<td><span><?php echo $orderItems['total_amount']; ?></span></td>
<?php
$status = $orderItems['status'];
$style = '';
$textColor = '';
$borderColor = '';
switch ($status) {
case 'TO SHIP':
$borderColor = 'mint';
$textColor = 'min'; // Change this to match the text color you prefer
break;
case 'TO PAY':
$borderColor = '#E0EA00';
$textColor = '#E0EA00';
break;
case 'TO RECEIVE':
$borderColor = '#20FF5A';
$textColor = '#20FF5A';
break;
case 'COMPLETED':
$borderColor = '#2098FF';
$textColor = '#2098FF'; // Change this to match the text color you prefer
break;
case 'TO REFUND':
$borderColor = '#FF5320';
$textColor = '#FF5320';
break;
default:
// Default styles if the status doesn't match any case
$borderColor = '#464646';
$textColor = '#464646';
}
// Generating style attribute based on the selected colors
$style = "display: flex; height: 15px;font-weight:400; width:90px; margin-top:10px; font-size:10px !important; justify-content:center; align-items:center; padding: 10px; border: 3px solid $borderColor; border-radius: 30px; color: $textColor;";
?>
<td><span style="<?php echo $style; ?>"> <p><?php echo $status; ?></p></span></td>
<td><span style="text-transform:capitalize"><?php echo $orderItems['shipping_address']['shipping_first_name']; ?></span></td>
<td ><span><?php echo $orderItems['total_amount']; ?></span></td>
<td style="display:flex; justify-content:center; margin-top:-4px;">
<span onclick="editVendorOrder('<?php echo $orderItems['_id'] ?>');">
<a class="mdi mdi-circle-edit-outline" style="font-size: 20px;"></a>
@ -286,10 +336,26 @@ if ($_SESSION["isCustomer"] == true) {
?>
</tbody>
</table>
<!-- <button id="exportBtn">Export to CSV</button> -->
</div>
<div id="pagination"></div>
<!-- <div id="pagination"></div> -->
</div>
<script>
// Initialize Metro UI components
// var tables = document.querySelectorAll('[data-role="table"]');
// tables.forEach(function(table) {
// new METRO.Table(table);
// });
// document.getElementById("exportBtn").addEventListener("click", function() {
// var table = document.querySelector('#order-table')._metroTable;
// table.export('CSV', 'all', 'table-export.csv', {
// csvDelimiter: "\t",
// csvNewLine: "\r\n",
// includeHeader: true
// });
// });
</script>
<script>
var sessionToken = '<?php echo isset($_SESSION["token"]) ? $_SESSION["token"] : ""; ?>';
var email = '<?php echo isset($_SESSION["email"]) ? $_SESSION["email"] : ""; ?>';
var password = '<?php echo isset($_SESSION["password"]) ? $_SESSION["password"] : ""; ?>';
@ -391,21 +457,22 @@ if ($_SESSION["isCustomer"] == true) {
});
}
function createPagination() {
const paginationContainer = document.getElementById('pagination');
// function createPagination() {
// const paginationContainer = document.getElementById('pagination');
for (let i = 1; i <= totalPages; i++) {
// created a tag
const pageButton = document.createElement('a');
// created class for a tag
pageButton.className = "page-btn page-" + i
pageButton.textContent = i;
pageButton.addEventListener('click', () => showPage(i));
paginationContainer.appendChild(pageButton);
}
}
// for (let i = 1; i <= totalPages; i++) {
// // created a tag
// const pageButton = document.createElement('a');
// // created class for a tag
// pageButton.className = "page-btn page-" + i
// pageButton.style="margin:5px"
// pageButton.textContent = i;
// pageButton.addEventListener('click', () => showPage(i));
// paginationContainer.appendChild(pageButton);
// }
// }
createPagination();
// createPagination();
showPage(1); // Show the first page by default
</script>
@ -421,15 +488,25 @@ if ($_SESSION["isCustomer"] == true) {
</div>
<div class="ec-vendor-card-body">
<div class="ec-vendor-card-table">
<table class="table ec-table">
<table class="table ec-table"
id="order-table"
data-role="table"
data-searching="true"
data-filtering="true"
data-sorting="true"
data-show-rows-steps="5,10,20,-1"
data-horizontal-scroll="true"
data-rownum="true"
data-table-info-title="Display from $1 to $2 of $3 product(s)"
>
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">Regular Price</th>
<th scope="col">Sale Price</th>
<th scope="col">Minimum Order</th>
<th scope="col">Stock</th>
<th data-sortable="false" scope="col">Image</th>
<th data-sortable="true" scope="col">Name</th>
<th data-sortable="true" scope="col">Regular Price</th>
<th data-sortable="true" scope="col">Sale Price</th>
<th data-sortable="true" scope="col">Minimum Order</th>
<th data-sortable="true" scope="col">Stock</th>
</tr>
</thead>
@ -438,7 +515,9 @@ if ($_SESSION["isCustomer"] == true) {
$products = productListVendor($vendorId);
$totalProducts = count($products);
$displayLimit = 5;
// for ($i = 0; $i < min($totalProducts, $displayLimit); $i++) {
for ($i = 0; $i < min($totalProducts, $displayLimit); $i++) {
$product = $products[$i];
?>
<tr>
@ -470,9 +549,9 @@ if ($_SESSION["isCustomer"] == true) {
</td>
<td style="max-width:300px;"><span class="text-truncate"><?php echo $product['product_name']; ?></span></td>
<td><span><?php echo $product['regular_price']; ?></span></td>
<td><span><?php echo $product['sale_price']; ?></span></td>
<td><span><?php echo $product['minimum_order']; ?></span></td>
<td><span><?php echo $product['stock']; ?></span></td>
<td><span><?php echo !empty($product['sale_price']) ?$product['sale_price']: "N/A"; ?></span></td>
<td><span><?php echo !empty($product['minimum_order']) ?$product['minimum_order']: "N/A";?></span></td>
<td><span><?php echo !empty($product['stock']) ?$product['stock']: "0"; ?></span></td>
</tr>
<?php
}
@ -480,7 +559,7 @@ if ($_SESSION["isCustomer"] == true) {
</tbody>
</table>
</div>
<div id="pagination"></div>
<!-- <div id="pagination"></div> -->
</div>
</div>
<!-- 02-26-2024 Stacy commented out -->
@ -847,7 +926,7 @@ if ($_SESSION["isCustomer"] == true) {
<script src="assets/js/vendor/bootstrap.min.js"></script>
<script src="assets/js/vendor/jquery-migrate-3.3.0.min.js"></script>
<script src="assets/js/vendor/modernizr-3.11.2.min.js"></script>
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<!--Plugins JS-->
<script src="assets/js/plugins/swiper-bundle.min.js"></script>
<script src="assets/js/plugins/nouislider.js"></script>

View File

@ -70,6 +70,8 @@ if ($_SESSION["isCustomer"] == true) {
<link rel="stylesheet" href="assets/css/style2.css" />
<link rel="stylesheet" href="assets/css/responsive.css" />
<link rel="stylesheet" href="https://cdn.metroui.org.ua/current/metro.css">
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<!-- Background css -->
<link rel="stylesheet" id="bg-switcher-css" href="assets/css/backgrounds/bg-4.css">
<style>
@ -206,15 +208,26 @@ if ($_SESSION["isCustomer"] == true) {
<div id="payments" class="tab-content active">
<!-- Gelo added vendor payments tab -->
<table class="table ec-table">
<table class="table ec-table"
id="order-table" style="overflow-x: auto;"
data-role="table"
data-pagination="true"
data-searching="true"
data-filtering="true"
data-sorting="true"
data-show-rows-steps="5,10,20,-1"
data-horizontal-scroll="true"
data-rownum="true"
data-table-info-title="Display from $1 to $2 of $3 payment(s)"
>
<thead>
<tr>
<th scope="col">Payment Method</th>
<th scope="col">Amount</th>
<th scope="col">Status</th>
<th scope="col">Description</th>
<th scope="col">Date Created</th>
<th scope="col">Action</th>
<th data-sortable="true" scope="col">Payment Method</th>
<th data-sortable="true" scope="col">Amount</th>
<th data-sortable="true" scope="col">Status</th>
<th data-sortable="true" scope="col">Description</th>
<th data-sortable="true" scope="col">Date Created</th>
<th data-sortable="true" scope="col">Action</th>
</tr>
</thead>
<tbody id="paymentsTableBody">
@ -250,7 +263,7 @@ if ($_SESSION["isCustomer"] == true) {
</tbody>
</table>
</div>
<div id="pagination"></div>
<!-- <div id="pagination"></div> -->
<script>
@ -286,21 +299,21 @@ if ($_SESSION["isCustomer"] == true) {
});
}
function createPagination() {
const paginationContainer = document.getElementById('pagination');
// function createPagination() {
// const paginationContainer = document.getElementById('pagination');
for (let i = 1; i <= totalPages; i++) {
// created a tag
const pageButton = document.createElement('a');
// created class for a tag
pageButton.className = "page-btn page-" + i
pageButton.textContent = i;
pageButton.addEventListener('click', () => showPage(i));
paginationContainer.appendChild(pageButton);
}
}
// for (let i = 1; i <= totalPages; i++) {
// // created a tag
// const pageButton = document.createElement('a');
// // created class for a tag
// pageButton.className = "page-btn page-" + i
// pageButton.textContent = i;
// pageButton.addEventListener('click', () => showPage(i));
// paginationContainer.appendChild(pageButton);
// }
// }
createPagination();
// createPagination();
showPage(1); // Show the first page by default
</script>
<script>
@ -885,6 +898,8 @@ if ($_SESSION["isCustomer"] == true) {
<script src="assets/js/vendor/jquery.magnific-popup.min.js"></script>
<script src="assets/js/plugins/jquery.sticky-sidebar.js"></script>
<script src="assets/js/plugins/nouislider.js"></script>
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<script>
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))