let reviews = [];
const url = window.location.href;
const productId = getProductId(url);
createReviewForm();
function getData() {
fetch(
`https://agencyapi.alltheapps.io/api/agency_app/reviews?product_id=${productId}`
)
.then((response) => response.json())
.then((data) => {
//console.log("Reviews:", data);
reviews = data.data.reverse();
})
.catch((error) => console.error(error));
}
getData();
// This is for Show Reviews and call in getData
function appendReviews() {
// Array containing review data
// const reviews = [
// {
// user_name: "Mary Stemm",
// rating: 5,
// description:
// "Everything 😍😍😍 Very professional and kind!!! Took great care of our house like they were working on their own!!! Fantastic job... couldn't be more ...",
// },
// {
// user_name: "John Doe",
// rating: 4,
// description:
// "Good service overall, but they could improve on timing. Very friendly staff!",
// },
// {
// user_name: "Jane Smith",
// rating: 5,
// description:
// "Exceptional work! They went above and beyond to ensure everything was perfect.",
// },
// {
// user_name: "Alice Johnson",
// rating: 3,
// description:
// "Average experience, some aspects were good, others not so much.",
// },
// {
// user_name: "Bob Brown",
// rating: 2,
// description: "Not satisfied with the service. It needs improvement.",
// },
// ];
let currentPage = 1;
const reviewsPerPage = 5;
// Function to create and style review elements
function createReview(review) {
// Create a container for the review
const reviewContainer = document.createElement("div");
reviewContainer.style.display = "flex";
reviewContainer.style.flexDirection = "column";
reviewContainer.style.width = "100%";
reviewContainer.style.border = "1px solid #ddd";
reviewContainer.style.borderRadius = "8px";
reviewContainer.style.padding = "16px";
reviewContainer.style.marginBottom = "16px";
reviewContainer.style.boxShadow = "0 2px 8px rgba(0,0,0,0.1)";
reviewContainer.style.boxSizing = "border-box";
reviewContainer.style.backgroundColor = "#f9f9f9";
// Create a container for the reviewer information
const reviewerContainer = document.createElement("div");
reviewerContainer.style.display = "flex";
reviewerContainer.style.alignItems = "center";
reviewerContainer.style.marginBottom = "8px";
// Create the profile picture placeholder
// const profilePic = document.createElement("div");
// profilePic.style.width = "40px";
// profilePic.style.height = "40px";
// profilePic.style.borderRadius = "50%";
// profilePic.style.backgroundColor = "#ccc";
// profilePic.style.marginRight = "12px";
// Create the reviewer name
const reviewerName = document.createElement("div");
reviewerName.style.fontWeight = "bold";
reviewerName.style.fontSize = "20px";
reviewerName.style.marginRight = "12px";
reviewerName.textContent = review.user_name;
reviewerName.style.color = "#333";
// Create the star rating
const starRating = document.createElement("div");
for (let i = 0; i < 5; i++) {
const star = document.createElement("span");
star.textContent = i < review.rating ? "★" : "☆";
star.style.fontSize = "30px";
star.style.color = "#ffa500";
starRating.appendChild(star);
}
const createData = document.createElement("div");
createData.style.marginLeft = "auto";
createData.style.fontSize = "13px";
const date = new Date(review.created_date);
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
createData.textContent = `${month}/${day}/${year}`;
createData.style.color = "#777";
// Create the review text
const reviewText = document.createElement("div");
reviewText.style.marginTop = "8px";
reviewText.style.fontSize = "16px";
reviewText.textContent = review.description;
reviewText.style.color = "#555";
// Append the elements to their respective containers
// reviewerContainer.appendChild(profilePic);
reviewerContainer.appendChild(starRating);
// reviewerContainer.appendChild(reviewerName);
reviewerContainer.appendChild(createData);
reviewContainer.appendChild(reviewerContainer);
reviewContainer.appendChild(reviewerName);
reviewContainer.appendChild(reviewText);
// Append the review container to the main div
const mainDiv = document.getElementById("main");
mainDiv.appendChild(reviewContainer);
}
// Function to display reviews with pagination
function displayReviews(page) {
const start = (page - 1) * reviewsPerPage;
const end = page * reviewsPerPage;
const paginatedReviews = reviews.slice(start, end);
// Clear existing reviews
const mainDiv = document.getElementById("main");
mainDiv.innerHTML = "";
// Display paginated reviews
paginatedReviews.forEach(createReview);
// Update pagination controls
updatePaginationControls(page);
}
// pagination
function updatePaginationControls(page) {
const totalPages = Math.ceil(reviews.length / reviewsPerPage);
const hasNextPage = page < totalPages;
const hasPrevPage = page > 1;
// Clear existing pagination controls
const paginationControls = document.getElementById("pagination-controls");
paginationControls.innerHTML = "";
// Create Previous button
const prevButton = document.createElement("button");
prevButton.style.marginRight = "8px";
prevButton.textContent = "Previous";
prevButton.disabled = !hasPrevPage;
prevButton.addEventListener("click", () => displayReviews(page - 1));
prevButton.style.padding = "8px 16px";
prevButton.style.border = "none";
prevButton.style.borderRadius = "4px";
prevButton.style.backgroundColor = "#f2f2f2";
prevButton.style.color = "#333";
prevButton.style.fontWeight = "bold";
prevButton.style.cursor = "pointer";
prevButton.style.opacity = hasPrevPage ? "1" : "0.5";
prevButton.addEventListener("mouseenter", () => {
prevButton.style.backgroundColor = "#e6e6e6";
});
prevButton.addEventListener("mouseleave", () => {
prevButton.style.backgroundColor = "#f2f2f2";
});
paginationControls.appendChild(prevButton);
// Create page numbers
for (let i = 1; i <= totalPages; i++) {
const pageButton = document.createElement("button");
pageButton.style.marginRight = "8px";
pageButton.textContent = i;
pageButton.disabled = page === i;
pageButton.addEventListener("click", () => displayReviews(i));
pageButton.style.padding = "8px 16px";
pageButton.style.border = "none";
pageButton.style.borderRadius = "4px";
pageButton.style.backgroundColor = page === i ? "#333" : "#f2f2f2";
pageButton.style.color = page === i ? "#fff" : "#333";
pageButton.style.fontWeight = "bold";
pageButton.style.cursor = "pointer";
pageButton.addEventListener("mouseenter", () => {
pageButton.style.backgroundColor = page === i ? "#333" : "#e6e6e6";
pageButton.style.color = page === i ? "#fff" : "#333";
});
pageButton.addEventListener("mouseleave", () => {
pageButton.style.backgroundColor = page === i ? "#333" : "#f2f2f2";
pageButton.style.color = page === i ? "#fff" : "#333";
});
paginationControls.appendChild(pageButton);
}
// Create Next button
const nextButton = document.createElement("button");
nextButton.textContent = "Next";
nextButton.disabled = !hasNextPage;
nextButton.addEventListener("click", () => displayReviews(page + 1));
nextButton.style.padding = "8px 16px";
nextButton.style.border = "none";
nextButton.style.borderRadius = "4px";
nextButton.style.backgroundColor = "#f2f2f2";
nextButton.style.color = "#333";
nextButton.style.fontWeight = "bold";
nextButton.style.cursor = "pointer";
nextButton.style.opacity = hasNextPage ? "1" : "0.5";
nextButton.addEventListener("mouseenter", () => {
nextButton.style.backgroundColor = "#e6e6e6";
});
nextButton.addEventListener("mouseleave", () => {
nextButton.style.backgroundColor = "#f2f2f2";
});
paginationControls.appendChild(nextButton);
}
// Create a container for all the reviews
const mainDiv = document.createElement("div");
mainDiv.id = "main";
mainDiv.style.display = "flex";
mainDiv.style.flexDirection = "column";
mainDiv.style.alignItems = "center";
mainDiv.style.padding = "16px";
mainDiv.style.boxSizing = "border-box";
document.getElementById("review").appendChild(mainDiv);
// Create pagination controls container
const paginationControls = document.createElement("div");
paginationControls.id = "pagination-controls";
paginationControls.style.display = "flex";
paginationControls.style.justifyContent = "center";
paginationControls.style.marginTop = "16px";
document.getElementById("review").appendChild(paginationControls);
// Display the first page of reviews
displayReviews(currentPage);
// Function to create and style review form
// Call the function to create the review form
}
// This is for creating Review Form
function createReviewForm() {
// Create the review form container
const reviewFormContainer = document.createElement("div");
reviewFormContainer.style.display = "none";
reviewFormContainer.style.marginTop = "20px";
reviewFormContainer.style.padding = "20px";
reviewFormContainer.style.border = "1px solid #ddd";
reviewFormContainer.style.borderRadius = "8px";
reviewFormContainer.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.1)";
reviewFormContainer.style.width = "100%";
reviewFormContainer.style.boxSizing = "border-box";
// Create the close button
const closeReviewForm = document.createElement("span");
closeReviewForm.textContent = "×";
closeReviewForm.style.float = "right";
closeReviewForm.style.fontSize = "20px";
closeReviewForm.style.cursor = "pointer";
reviewFormContainer.appendChild(closeReviewForm);
// Create the rating question
const ratingQuestion = document.createElement("p");
ratingQuestion.textContent = "How would you rate your experience?";
reviewFormContainer.appendChild(ratingQuestion);
// Create the rating emojis container
const ratingContainer = document.createElement("div");
ratingContainer.style.display = "flex";
ratingContainer.style.justifyContent = "center";
// const emojis = ["😡", "🙁", "😐", "🙂", "😁"];
// emojis.forEach((emoji) => {
// const ratingEmoji = document.createElement("span");
// ratingEmoji.textContent = emoji;
// ratingEmoji.style.fontSize = "24px";
// ratingEmoji.style.margin = "0 5px";
// ratingEmoji.style.cursor = "pointer";
// ratingContainer.appendChild(ratingEmoji);
// });
// reviewFormContainer.appendChild(ratingContainer);
// dd
// Create the rating stars container
var selectedStars = 0;
const ratingStarsContainer = document.createElement("div");
ratingStarsContainer.style.display = "flex";
ratingStarsContainer.style.justifyContent = "left";
ratingStarsContainer.style.marginTop = "10px";
reviewFormContainer.appendChild(ratingStarsContainer);
// Create an array to store the star elements
const stars = [];
// Create 5 empty stars
for (let i = 0; i < 5; i++) {
const star = document.createElement("span");
star.textContent = "☆";
star.style.color = "#f1c40f";
star.style.fontSize = "30px";
star.style.cursor = "pointer";
star.addEventListener("click", () => {
// Set all stars to empty
stars.forEach((s) => (s.textContent = "☆"));
// Set the clicked star and all stars to its left to yellow
for (let j = 0; j <= i; j++) {
stars[j].textContent = "★";
stars[j].style.color = "#f1c40f";
}
// Save the number of selected stars
selectedStars = i + 1;
//console.log("Selected stars:", selectedStars);
// Use the selectedStars variable as needed
});
stars.push(star);
ratingStarsContainer.appendChild(star);
}
var emojiContainer = document.createElement("div");
emojiContainer.className = "emoji-container";
reviewFormContainer.appendChild(emojiContainer);
emojiContainer.appendChild(ratingStarsContainer);
const reviwerName = document.createElement("input");
reviwerName.placeholder = "Please Enter Your Name";
reviwerName.style.width = "100%";
reviwerName.style.marginTop = "10px";
reviwerName.style.boxSizing = "border-box";
reviwerName.type = "text";
reviwerName.style.padding = "10px";
reviwerName.style.border = "1px solid #ddd";
reviwerName.style.borderRadius = "5px";
reviwerName.style.fontFamily = "Arial, sans-serif";
reviewFormContainer.appendChild(reviwerName);
// Create the review text area
const reviewText = document.createElement("textarea");
reviewText.placeholder = "Please tell us about your experience:";
reviewText.style.width = "100%";
reviewText.style.marginTop = "10px";
reviewText.style.boxSizing = "border-box";
reviewText.rows = "4";
reviewText.style.padding = "10px";
reviewText.style.border = "1px solid #ddd";
reviewText.style.borderRadius = "5px";
reviewText.style.fontFamily = "Arial, sans-serif";
reviewFormContainer.appendChild(reviewText);
// Create the email input field
const reviewEmail = document.createElement("input");
reviewEmail.type = "email";
reviewEmail.placeholder = "Your email address (optional):";
reviewEmail.style.width = "100%";
reviewEmail.style.marginTop = "10px";
reviewEmail.style.boxSizing = "border-box";
reviewEmail.style.padding = "10px";
reviewEmail.style.border = "1px solid #ddd";
reviewEmail.style.borderRadius = "5px";
reviewEmail.style.fontFamily = "Arial, sans-serif";
reviewFormContainer.appendChild(reviewEmail);
// Create the send button
const sendBtn = document.createElement("button");
sendBtn.textContent = "Send";
sendBtn.style.padding = "10px 20px";
sendBtn.style.backgroundColor = "#28a745";
sendBtn.style.color = "white";
sendBtn.style.border = "none";
sendBtn.style.borderRadius = "5px";
sendBtn.style.cursor = "pointer";
sendBtn.style.fontSize = "16px";
sendBtn.style.width = "100%";
sendBtn.style.marginTop = "10px";
reviewFormContainer.appendChild(sendBtn);
sendBtn.addEventListener("click", () => {
var feedback = document.querySelector("textarea").value;
var email = document.querySelector("input[type='email']").value;
var name = document.querySelector("input[type='text']").value;
// //console.log("Feedback:", feedback);
// //console.log("Email:", email);
// //console.log("Emoji:", emojiSelected);
const payload = {
description: feedback,
email: email,
user_name: name,
product_id: productId,
websiteId: " ",
product_name: document.getElementsByClassName(
"hl-product-detail-product-name"
)[0].textContent,
rating: selectedStars,
};
//console.log("Data:", payload);
//console.log("Product ID:", productId);
document.querySelector("textarea").value = "";
document.querySelector("input[type='email']").value = "";
document.querySelector("input[type='text']").value = "";
emojiSelected = "";
fetch("https://agencyapi.alltheapps.io/api/agency_app/reviews", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
})
.then((response) => response.json())
.then((data) => {
//console.log("API response:", data);
getData();
// Add your logic to handle the API response here
})
.catch((error) => {
console.error("API error:", error);
// Add your error handling logic here
});
// document.querySelector(".selected").style.fontSize = "24px";
// Test APi
// $.ajax({
// url: "https://3e47ba7c9ecc4298b74c7bd8de2f7a1c.api.mockbin.io/",
// method: "POST",
// data: JSON.stringify(data),
// contentType: "application/json",
// success: function (response) {
// //console.log("API response:", response);
// // Add your logic to handle the API response here
// },
// error: function (error) {
// console.error("API error:", error);
// // Add your error handling logic here
// },
// });
});
// Append the review form container to the specified element
const reviewDiv = document.getElementById("review");
reviewDiv.appendChild(reviewFormContainer);
// Create the write review button
const writeReviewBtn = document.createElement("button");
writeReviewBtn.textContent = "Write Review";
writeReviewBtn.style.padding = "10px 20px";
writeReviewBtn.style.backgroundColor = "#28a745";
writeReviewBtn.style.color = "white";
writeReviewBtn.style.border = "none";
writeReviewBtn.style.borderRadius = "5px";
writeReviewBtn.style.cursor = "pointer";
writeReviewBtn.style.fontSize = "16px";
writeReviewBtn.style.marginTop = "10px";
writeReviewBtn.style.display = "block";
writeReviewBtn.style.marginLeft = "auto";
writeReviewBtn.style.marginRight = "auto";
reviewDiv.appendChild(writeReviewBtn);
// Add event listeners
writeReviewBtn.addEventListener("click", () => {
reviewFormContainer.style.display = "block";
writeReviewBtn.style.display = "none";
});
closeReviewForm.addEventListener("click", () => {
reviewFormContainer.style.display = "none";
writeReviewBtn.style.display = "block";
});
}
// this will split the product id from the url
function getProductId(url) {
// Split the URL by '?' to isolate the part before query parameters
const [baseUrl] = url.split("?");
// Split the baseUrl by '/' and store the parts in an array
const parts = baseUrl.split("/");
// Find the index of 'product' in the array and get the next element, which is the product ID
const productIndex = parts.indexOf("product");
if (productIndex !== -1 && productIndex + 1 < parts.length) {
return parts[productIndex + 1];
}
// Return null if 'product' is not found or there is no product ID after 'product'
return null;
}
// show Average
function showAverage() {
//console.log("workign:");
const div = document.createElement("div");
div.id = "rating";
const averageRating = calculateAverageRating(reviews);
const starRating = document.createElement("div");
starRating.className = "star-rating";
starRating.style.display = "flex";
starRating.style.alignItems = "center";
starRating.style.marginTop = "10px";
div.appendChild(starRating);
// Create the filled stars
for (let i = 0; i < averageRating; i++) {
const filledStar = document.createElement("span");
filledStar.textContent = "★";
filledStar.style.color = "#f1c40f";
filledStar.style.fontSize = "30px";
starRating.appendChild(filledStar);
}
// Create the empty stars
for (let i = averageRating; i < 5; i++) {
const emptyStar = document.createElement("span");
emptyStar.textContent = "☆";
emptyStar.style.color = "#f1c40f";
emptyStar.style.fontSize = "30px";
starRating.appendChild(emptyStar);
}
// Create the "hlo" text
const totalReviews = document.createElement("span");
totalReviews.textContent = ` (${reviews.length} + reviews)`;
totalReviews.style.marginLeft = "10px";
totalReviews.style.fontSize = "14px";
totalReviews.style.cursor = "pointer";
totalReviews.style.textDecoration = "underline";
starRating.appendChild(totalReviews);
totalReviews.addEventListener("mouseover", () => {
totalReviews.style.textDecoration = "underline";
});
totalReviews.addEventListener("mouseout", () => {
totalReviews.style.textDecoration = "none";
});
// Add click event listener to scroll to review section
totalReviews.addEventListener("click", () => {
const reviewSection = document.getElementById("review");
reviewSection.scrollIntoView({ behavior: "smooth" });
});
// div.innerText = averageRating;
function calculateAverageRating(reviews) {
let totalRating = 0;
for (let i = 0; i < reviews.length; i++) {
// totalRating += reviews[i].rating;
totalRating += parseInt(reviews[i].rating);
}
const averageRating = totalRating / reviews.length;
//console.log("Average Rating:", averageRating);
return `${Math.ceil(averageRating.toFixed(1))}`;
}
const findButton = setInterval(function () {
if (document.getElementById("add-to-cart-btn")) {
const addToCartBtn = document.getElementById("add-to-cart-btn");
if (document.getElementById("rating")) {
document.getElementById("rating").remove();
addToCartBtn.parentNode.insertBefore(div, addToCartBtn);
} else {
addToCartBtn.parentNode.insertBefore(div, addToCartBtn);
}
clearInterval(findButton);
}
}, 1000);
}