//File: trending-products.js
document.addEventListener('DOMContentLoaded', function() {
    const apiURL = 'controlls/api/products.php?sortbylike=ASC&sortbytime=DESC';

    // شناسه div های تب‌ها
    const tabs = {
        sale: document.getElementById('saleProducts'),
        featured: document.getElementById('featuredProducts'),
        rated: document.getElementById('ratedProducts')
    };

    function createProductCard(product) {
        const price = parseFloat(product.price) || 0;
const discount = parseFloat(product.discount) || 0;
        const discountedPrice = discount > 0
    ? (price - (price * discount / 100)).toFixed(2)
    : price.toFixed(2);
    let priceHtml = "";
    if (discount > 0) {
    priceHtml = `
        <span class="text-gray-400 text-md font-[600] text-decoration-line-through">
            $${price.toFixed(2)}
        </span>
        <span class="text-heading text-md font-[600]">
            $${discountedPrice} <span class="text-gray-500 font-normal">/Qty</span>
        </span>
    `;
} else {
    priceHtml = `
        <span class="text-heading text-md font-[600]">
            $${price.toFixed(2)} <span class="text-gray-500 font-normal">/Qty</span>
        </span>
    `;
}

        return `
        <div class="2xl:w-3/12 flex-grow-0 flex-shrink-0 basis-auto xl:w-4/12 md:w-6/12" data-aos="fade-up" data-aos-duration="200">
            <div class="product-card h-full p-16 border border-gray-100 hover-border-main-600 rounded-16 relative transition-2">
                <div class="product-card__thumb rounded-8 bg-gray-50 relative">
                    <a href="product-details.php?id=${product.id}" class="w-full h-full flex items-center justify-center">
                        <img src="controlls/uploads/${product.image_path}" alt="${product.name}" class="!w-auto max-w-[unset]">
                    </a>
                    <div class="absolute inset-block-start-0 inset-inline-start-0 mt-16 ms-16 z-[1] flex flex-col gap-8">
                        ${product.discount > 0 ? `<span class="text-main-two-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">-${product.discount}%</span>` : ''}
                        ${product.hot === "1" ? `<span class="text-neutral-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">HOT</span>` : ''}
                    </div>
                </div>
                <div class="product-card__content mt-16 w-full">
                    <h6 class="title text-lg font-[600] my-16"><a href="product-details.php?id=${product.id}" class="link text-line-2">${product.name}</a></h6>
                    <div class="flex items-center gap-6">
                        <div class="flex items-center gap-8">
                            ${[...Array(5)].map((_, i) => `<span class="text-15 font-[500] ${i < product.average_rating ? 'text-warning-600' : ''} flex"><i class="ph-fill ph-star"></i></span>`).join('')}
                        </div>
                        <span class="text-xs font-[500] text-gray-500">${product.average_rating || 0}</span>
                        <span class="text-xs font-[500] text-gray-500">(${product.total_ratings})</span>
                    </div>
                  
                      <div class="product-card__price mt-16 mb-30">
 
                                    ${priceHtml}
                                </div>
                                                                <a href="cart.html" class="btn bg-gray-50 text-heading hover-bg-main-600 hover-text-white py-11 px-24 rounded-8 flex items-center justify-center gap-8 font-[500]">Add To Cart <i class="ph ph-shopping-cart"></i></a>

                </div>
            </div>
        </div>`;
    }

    async function fetchProducts() {
        try {
            const res = await fetch(apiURL);
            const data = await res.json();

            // فقط یک بار اضافه کردن کارت‌ها
            if(tabs.sale.children.length === 0) {
                data.forEach(product => {
                    tabs.featured.insertAdjacentHTML('beforeend', createProductCard(product));
                    tabs.sale.insertAdjacentHTML('beforeend', createProductCard(product));

                    tabs.rated.insertAdjacentHTML('beforeend', createProductCard(product));
                });
            }
        } catch (error) {
            console.error('خطا در دریافت داده‌ها:', error);
        }
    }

    fetchProducts();
});




document.addEventListener("DOMContentLoaded", function () {
    const container = document.querySelector(".popular-products-three .row");

    // نمایش لودینگ
    container.innerHTML = `<p class="text-center w-full py-4">در حال بارگذاری محصولات...</p>`;

    fetch("controlls/api/products.php")
        .then((response) => {
            if (!response.ok) throw new Error("خطا در دریافت داده‌ها");
            return response.json();
        })
        .then((data) => {
            container.innerHTML = ""; // پاک کردن لودینگ

            data.forEach((p) => {
                const avg = Math.round(p.average_rating);
                let stars = "";
                for (let i = 1; i <= 5; i++) {
                    stars += i <= avg
                        ? '<span class="text-warning-600 flex"><i class="ph-fill ph-star"></i></span>'
                        : '<span class="text-gray-300 flex"><i class="ph-fill ph-star"></i></span>';
                }

                container.innerHTML += `
                    <div class="custom-2xl:w-3/12 flex-grow-0 flex-shrink-0 basis-auto 2xl:w-4/12 md:w-6/12" data-aos="fade-up">
                        <div class="product-card h-full p-16 border border-gray-100 hover-border-main-600 rounded-16 relative transition-2">
                            <div class="product-card__thumb rounded-8 bg-gray-50 relative">
                                <a href="product-details-two.html" class="w-full h-full flex items-center justify-center">
                                    <img src="controlls/uploads/${p.image_path}" alt="${p.name}" class="!w-auto max-w-[unset]">
                                </a>
                                <div class="absolute inset-block-start-0 inset-inline-start-0 mt-16 ms-16 z-[1] flex flex-col gap-8">
                                    <span class="text-main-two-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">${p.discount}%</span>
                                    <span class="text-neutral-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">HOT</span>
                                </div>
                            </div>
                            <div class="product-card__content mt-16 w-full">
                                <h6 class="title text-lg font-[600] my-16">
                                    <a href="product-details-two.html" class="link text-line-2">${p.name}</a>
                                </h6>
                                <div class="flex items-center gap-6">
                                    <div class="flex items-center gap-8">
                                        ${stars}
                                        <span class="text-xs text-gray-500">(${p.total_ratings})</span>
                                    </div>
                                </div>
                                <span class="py-2 px-8 text-xs rounded-[50rem] text-main-two-600 bg-main-two-50 mt-16">Fulfilled by Marketpro</span>
                                <div class="product-card__price mt-16 mb-30">
                                    <span class="text-gray-400 text-md font-[600] text-decoration-line-through">$${p.price}</span>
                                    <span class="text-heading text-md font-[600]">$14.99 <span class="text-gray-500 font-normal">/Qty</span></span>
                                </div>
                                <a href="cart.html" class="btn bg-gray-50 text-heading hover-bg-main-600 hover-text-white py-11 px-24 rounded-8 flex items-center justify-center gap-8 font-[500]">Add To Cart <i class="ph ph-shopping-cart"></i></a>
                            </div>
                        </div>
                    </div>
                `;
            });
        })
        .catch((error) => {
            console.error(error);
            container.innerHTML = `<p class="text-center text-red-500 py-4">خطا در بارگذاری محصولات!</p>`;
        });
});


// document.addEventListener("DOMContentLoaded", async function () {
//     const tabList = document.getElementById("pills-tabThree");
//     const tabContent = document.getElementById("pills-tabContentThree");

//     try {
//         const res = await fetch("controlls/api/products.php");
//         const products = await res.json();

//         // استخراج دسته‌ها از محصولات
//         const categories = [...new Set(products.map(p => p.category_id))];

//         // ساخت تب‌ها
//         let tabsHTML = `
//             <li class="nav-item" role="presentation">
//                 <button class="nav-link bt-tb-btn-t active"
//                         data-bs-toggle="pill"
//                         data-bs-target="#pills-all"
//                         type="button"
//                         role="tab"
//                         aria-selected="true">All</button>
//             </li>
//         `;

//         categories.forEach((catId, index) => {
//             const firstProduct = products.find(p => p.category_id === catId);
//             const catName = firstProduct ? firstProduct.category_name || `Category ${catId}` : `Category ${catId}`;
//             tabsHTML += `
//                 <li class="nav-item" role="presentation">
//                     <button class="nav-link bt-tb-btn-t ${index === 0 ? '' : ''}"
//                             data-bs-toggle="pill"
//                             data-bs-target="#pills-${catId}"
//                             type="button"
//                             role="tab">${catName}</button>
//                 </li>
//             `;
//         });

//         tabList.innerHTML = tabsHTML;

//         // ساخت تب محتواها
//         let allProductsHTML = '<div class="row g-4">';
//         products.forEach(p => {
//             const finalPrice = (p.discount > 0)
//                 ? (p.price - (p.price * p.discount / 100)).toFixed(2)
//                 : parseFloat(p.price).toFixed(2);

//             allProductsHTML += `
//                 <div class="xl:w-4/12 md:w-6/12">
//                     <div class="product-card p-16 border border-gray-100 hover-border-main-600 rounded-16 relative transition-2">
//                         <div class="product-card__thumb rounded-8 bg-gray-50 relative">
//                             <a href="product-details-two.html" class="flex items-center justify-center">
//                                 <img src="uploads/${p.image_path}" alt="${p.name}" class="!w-auto max-w-[unset]">
//                             </a>
//                             ${p.discount > 0 ? `
//                                 <div class="absolute top-0 left-0 mt-16 ms-16 z-[1]">
//                                     <span class="text-main-two-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">
//                                         -${p.discount}%
//                                     </span>
//                                 </div>` : ''
//                             }
//                         </div>
//                         <div class="product-card__content mt-16 w-full">
//                             <h6 class="title text-lg font-[600] my-16">
//                                 <a href="product-details-two.html" class="link text-line-2">${p.name}</a>
//                             </h6>
//                             <div class="product-card__price mt-16 mb-30">
//                                 ${p.discount > 0 ? `<span class="text-gray-400 text-md font-[600] text-decoration-line-through">$${p.price}</span>` : ''}
//                                 <span class="text-heading text-md font-[600]">$${finalPrice} <span class="text-gray-500 font-normal">/Qty</span></span>
//                             </div>
//                             <a href="cart.html" class="btn bg-gray-50 text-heading hover-bg-main-600 hover-text-white py-11 px-24 rounded-8 flex items-center justify-center gap-8 font-[500]">
//                                 Add To Cart <i class="ph ph-shopping-cart"></i>
//                             </a>
//                         </div>
//                     </div>
//                 </div>
//             `;
//         });
//         allProductsHTML += '</div>';

//         // اضافه کردن تب "All"
//         let tabsContentHTML = `
//             <div class="tab-pane fade show active" id="pills-all" role="tabpanel">
//                 ${allProductsHTML}
//             </div>
//         `;

//         // اضافه کردن تب هر دسته
//         categories.forEach(catId => {
//             let catProducts = products.filter(p => p.category_id === catId);
//             let catHTML = '<div class="row g-4">';
//             catProducts.forEach(p => {
//                 const finalPrice = (p.discount > 0)
//                     ? (p.price - (p.price * p.discount / 100)).toFixed(2)
//                     : parseFloat(p.price).toFixed(2);

//                 catHTML += `
//                     <div class="xl:w-4/12 md:w-6/12">
//                         <div class="product-card p-16 border border-gray-100 hover-border-main-600 rounded-16 relative transition-2">
//                             <div class="product-card__thumb rounded-8 bg-gray-50 relative">
//                                 <a href="product-details-two.html" class="flex items-center justify-center">
//                                     <img src="uploads/${p.image_path}" alt="${p.name}" class="!w-auto max-w-[unset]">
//                                 </a>
//                                 ${p.discount > 0 ? `
//                                     <div class="absolute top-0 left-0 mt-16 ms-16 z-[1]">
//                                         <span class="text-main-two-600 w-40 h-40 flex justify-center items-center bg-white rounded-[50%] shadow-sm text-xs font-[600]">
//                                             -${p.discount}%
//                                         </span>
//                                     </div>` : ''
//                                 }
//                             </div>
//                             <div class="product-card__content mt-16 w-full">
//                                 <h6 class="title text-lg font-[600] my-16">
//                                     <a href="product-details-two.html" class="link text-line-2">${p.name}</a>
//                                 </h6>
//                                 <div class="product-card__price mt-16 mb-30">
//                                     ${p.discount > 0 ? `<span class="text-gray-400 text-md font-[600] text-decoration-line-through">$${p.price}</span>` : ''}
//                                     <span class="text-heading text-md font-[600]">$${finalPrice} <span class="text-gray-500 font-normal">/Qty</span></span>
//                                 </div>
//                                 <a href="cart.html" class="btn bg-gray-50 text-heading hover-bg-main-600 hover-text-white py-11 px-24 rounded-8 flex items-center justify-center gap-8 font-[500]">
//                                     Add To Cart <i class="ph ph-shopping-cart"></i>
//                                 </a>
//                             </div>
//                         </div>
//                     </div>
//                 `;
//             });
//             catHTML += '</div>';
//             tabsContentHTML += `
//                 <div class="tab-pane fade" id="pills-${catId}" role="tabpanel">
//                     ${catHTML}
//                 </div>
//             `;
//         });

//         tabContent.innerHTML = tabsContentHTML;

//     } catch (error) {
//         console.error("Error loading products:", error);
//     }
// });
