document.addEventListener("DOMContentLoaded", async function() {
    // Get product id from URL (?id=2)
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('id');

    if (!productId) {
        document.getElementById('productDetails').innerHTML = "<p>No product found!</p>";
        return;
    }

    try {
        // Fetch product data from API
        const response = await fetch(`controlls/api/products.php?id=${productId}`);
        const product = await response.json();

        if (!product || !product.id) {
            document.getElementById('productDetails').innerHTML = "<p>Failed to load product details!</p>";
            return;
        }

        // Build dynamic HTML content
        const html = `
            <div class="flex items-center justify-center mb-24 flex-wrap gap-16 bg-color-one rounded-8 py-16 px-24 relative z-[1]">
                <img src="controlls/uploads/${product.image_path}" alt="Image"
                     class="absolute inset-block-start-0 inset-inline-start-0 w-full h-full z-[-1]">
                <div class="flex items-center gap-16">
                    <span class="text-white text-sm">Special Offer:</span>
                </div>
            </div>

            <h5 class="mb-12">${product.name}</h5>

            <div class="flex items-center flex-wrap gap-12">
                <span class="text-gray-900"><span class="text-gray-400">SKU:</span> #${product.id}</span>
            </div>

            <span class="mt-32 pt-32 text-gray-700 border-t border-gray-100 block"></span>
            <p class="text-gray-700">${product.description}</p>

            <div class="my-32 flex items-center gap-16 flex-wrap">
                <div class="flex items-center gap-8">
                    <div class="flex items-center gap-8 text-main-two-600">
                        <i class="ph-fill ph-seal-percent text-xl"></i>
                        ${product.discount ? '-' + product.discount + '%' : ''}
                    </div>
                    <h6 class="mb-0">USD ${product.price}</h6>
                </div>

                ${product.discount ? `
                <div class="flex items-center gap-8">
                    <span class="text-gray-700">Regular Price</span>
                    <h6 class="text-xl text-gray-400 mb-0 font-[500]">
                        USD ${(product.price * (1 - product.discount / 100)).toFixed(2)}
                    </h6>
                </div>` : ''}
            </div>

            <div class="mt-32">
                <h6 class="mb-16">Product Specifications</h6>
                <p><strong>Material:</strong> ${product.material}</p>
                <p><strong>Dimensions:</strong> ${product.dimensions}</p>
                <p><strong>Weight:</strong> ${product.weight} kg</p>
                <p><strong>Stock:</strong> ${product.stock}</p>
            </div>

            <div class="mt-32">
                <img src="uploads/${product.image_path}" alt="${product.name}" class="rounded-8 max-w-[400px]">
            </div>

            <a href="https://wa.me/?text=Hello, I want more info about ${product.name}."
               target="_blank"
               class="btn btn-black flex items-center justify-center gap-8 rounded-8 py-16 mt-24">
               <i class="ph ph-whatsapp-logo text-lg"></i> Request More Information
            </a>
        `;
     ; // تبدیل رشته به آرایه

    

 console.log("albums",product.albums);
 
//   renderProductImages(product.albums);

// const html_images=`   <div class="product-details__thumb-slider border border-gray-100 rounded-16">
//                                     <div class="">
//                                         <div class="product-details__thumb flex items-center justify-center h-full"><img
//                                                 src="images/product-details-two-thumb1.png" alt="Image"></div>
//                                     </div>
//                                     <div class="">
//                                         <div class="product-details__thumb flex items-center justify-center h-full"><img
//                                                 src="images/product-details-two-thumb2.png" alt="Image"></div>
//                                     </div>
//                                     <div class="">
//                                         <div class="product-details__thumb flex items-center justify-center h-full"><img
//                                                 src="images/product-details-two-thumb3.png" alt="Image"></div>
//                                     </div>
//                                     <div class="">
//                                         <div class="product-details__thumb flex items-center justify-center h-full"><img
//                                                 src="images/product-details-two-thumb1.png" alt="Image"></div>
//                                     </div>
//                                     <div class="">
//                                         <div class="product-details__thumb flex items-center justify-center h-full"><img
//                                                 src="images/product-details-two-thumb2.png" alt="Image"></div>
//                                     </div>
//                                 </div>
//                                 <div class="mt-24">
//                                     <div class="product-details__images-slider">
//                                         <div>
//                                             <div
//                                                 class="max-w-120 max-h-120 h-full flex items-center justify-center border border-gray-100 rounded-16 p-8">
//                                                 <img src="images/product-details-two-thumb1.png" alt="Image">
//                                             </div>
//                                         </div>
//                                         <div>
//                                             <div
//                                                 class="max-w-120 max-h-120 h-full flex items-center justify-center border border-gray-100 rounded-16 p-8">
//                                                 <img src="images/product-details-two-thumb2.png" alt="Image">
//                                             </div>
//                                         </div>
//                                         <div>
//                                             <div
//                                                 class="max-w-120 max-h-120 h-full flex items-center justify-center border border-gray-100 rounded-16 p-8">
//                                                 <img src="images/product-details-two-thumb3.png" alt="Image">
//                                             </div>
//                                         </div>
//                                         <div>
//                                             <div
//                                                 class="max-w-120 max-h-120 h-full flex items-center justify-center border border-gray-100 rounded-16 p-8">
//                                                 <img src="images/product-details-two-thumb1.png" alt="Image">
//                                             </div>
//                                         </div>
//                                         <div>
//                                             <div
//                                                 class="max-w-120 max-h-120 h-full flex items-center justify-center border border-gray-100 rounded-16 p-8">
//                                                 <img src="images/product-details-two-thumb2.png" alt="Image">
//                                             </div>
//                                         </div>
//                                     </div>
//                                 </div>`;
//                                 document.getElementById('album-products').innerHTML=html_images;
  





       document.getElementById('productDetails').innerHTML = html;
//         swiper.update();

        

    } catch (error) {
        console.error(error);
        document.getElementById('productDetails').innerHTML = "<p>Error loading product details!</p>";
    }
});

document.addEventListener("DOMContentLoaded", async () => {
  const container = document.getElementById("dealOfTheDay");

  try {
    // درخواست به API
    const response = await fetch("controlls/api/products.php/getDiscount");
    const products = await response.json();

    if (!Array.isArray(products) || products.length === 0) {
      container.innerHTML = "<p>No daily discounts are currently active.</p>";
      return;
    }

    // ساخت HTML برای هر محصول
    const html = products.map((product, index) => `
      <div class="2xl:w-4/12 md:w-6/12 w-full" data-aos="zoom-in" data-aos-duration="800">
        <div class="discount-three-item bg-img rounded-16 overflow-hidden relative">
          <div class="bg-img-custom">
            <img src="controlls/uploads/${product.image_path}" alt="${product.name}">
          </div>
          <div class="text-start p-4">
            <span class="font-[500] text-neutral-600 mb-4 uppercase block">
              ${product.discount}% discount
            </span>
            <h6 class="font-[600] mb-0 max-w-375">${product.name}</h6>
            <p class="mt-2">${product.description || ''}</p>
            <div class="mt-3 text-lg font-semibold">
              Price: $${product.price}
            </div>
            <div id="timer-${index}" class="mt-3 text-red-600 font-bold text-sm"></div>
            <a href="shop.html" class="btn btn-black rounded-[50rem] gap-8 mt-4 flex items-center inline-flex">
              Buy Now
              <span class="text-xl flex"><i class="ph ph-shopping-cart-simple"></i></span>
            </a>
          </div>
        </div>
      </div>
    `).join('');

    container.innerHTML = html;

    // راه‌اندازی تایمر برای هر محصول
    products.forEach((product, index) => {
      if (product.discount_until) {
        startCountdown(product.discount_until, `timer-${index}`);
      }
    });

  } catch (error) {
    console.error("خطا در دریافت تخفیف‌ها:", error);
    container.innerHTML = "<p>خطا در بارگذاری اطلاعات.</p>";
  }
});

// تابع شمارش معکوس
function startCountdown(endTime, elementId) {
  const timerElement = document.getElementById(elementId);
  const end = new Date(endTime).getTime();

  const updateTimer = () => {
    const now = new Date().getTime();
    const distance = end - now;

    if (distance <= 0) {
      timerElement.innerHTML = "Expired";
      clearInterval(interval);
      return;
    }

    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    timerElement.innerHTML = `
      ⏳ ${days}d ${hours}h ${minutes}m ${seconds}s
    `;
  };

  updateTimer();
  const interval = setInterval(updateTimer, 1000);
}




document.addEventListener("DOMContentLoaded", async () => {
    const dealContainer = document.getElementById("deal-content");

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

        if (!data || !data.id) {
            dealContainer.innerHTML = "<p class='text-center text-white py-5'>تخفیف روز در دسترس نیست.</p>";
            return;
        }

        const discountEnd = data.discount_until ? new Date(data.discount_until) : null;

        dealContainer.innerHTML = `
            <div class="2xl:w-6/12 flex-grow-0 flex-shrink-0 basis-auto lg:block hidden">
                <div class="relative px-24">
                    <ul class="products-group">
                        <li class="products-group__list pt-12">
                            <span class="w-32 h-32 border-[2] border-white rounded-[50%] flex items-center justify-center relative overflow-hidden bg-blur cursor-pointer">
                                <span class="w-12 h-12 rounded-[50%] bg-white"></span>
                            </span>
                            <div class="products-group__card product-card w-full p-16 border border-gray-100 hover-border-main-600 max-w-340 rounded-16 transition-2 bg-white absolute bottom-100 left-[50%] min-width-max-content rotate-10 transition-2">
                                <div class="product-card__thumb rounded-8 bg-gray-50 relative">
                                    <a href="product-details.php?id=${data.id}" class="w-full h-full flex items-center justify-center">
                                        <img src="controlls/uploads/${data.image_path}" alt="${data.name}" class="!w-auto max-w-[unset]">
                                    </a>
                                    <button type="button" class="z-[1] absolute right-0 inset-block-start-0 me-16 mt-16 text-neutral-600 text-xl flex items-center justify-center hover-text-main-two-600 wishlist-btn">
                                        <i class="ph-fill ph-heart text-main-two-600"></i>
                                    </button>
                                </div>
                                <div class="product-card__content mt-16 w-full">
                                    <h6 class="title text-2xl font-[600] my-8">
                                        <a href="product-details-two.html" class="link text-line-2">${data.name}</a>
                                    </h6>
                                    <div class="product-card__price mt-8 mb-8">
                                        <span class="text-neutral-600 text-lg font-[600]">$${data.price} USD</span>
                                        ${
                                            data.discount && data.discount > 0
                                                ? `<span class="text-gray-400 text-lg font-[600] text-decoration-line-through">${(data.price * (1 - data.discount / 100)).toFixed(2)}USD</span>`
                                                : ""
                                        }
                                    </div>
                                    <p class="text-gray-500 text-md mb-8">${data.description}</p>
                                    <div class="flex items-center gap-6">
                                        <span class="text-lg font-[500] text-warning-600 flex"><i class="ph-fill ph-star"></i></span>
                                        <span class="text-lg font-[500] text-gray-500">4.8</span>
                                        <span class="text-lg font-[500] text-gray-500">(${data.likes_count} Likes)</span>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                    <div class="text-end" data-aos="fade-up" data-aos-duration="600">
                        <img src="controlls/uploads/${data.image_path}" alt="${data.name}" class="pe-xxl-5 pe-lg-4 deals__img">
                    </div>
                </div>
            </div>

            <div class="2xl:w-6/12 flex-grow-0 flex-shrink-0 basis-auto" data-aos="zoom-in">
                <div class="p-56-px">
                    <div class="text-center border border-white rounded-80 rounded-top-right-0 p-56-px">
                        <div class="p-56-px bg-white rounded-80 rounded-top-right-0">
                            <div class="max-w-472 mx-auto">
                                <span class="text-white bg-neutral-600 py-8 px-16 rounded-[50rem] font-[500] text-md mb-32 text-uppercase">Only For Today</span>
                                <h3 class="mb-32 font-[500] text-uppercase">Deal of The Day</h3>
                                <p class="text-neutral-600">${data.description}</p>
                            </div>
                            <div class="mt-48">
                                <div class="countdown" id="countdown24">
                                    <ul class="countdown-list style-four flex items-center justify-center flex-wrap gap-24">
                                        <li><span id="days" class="flex items-center justify-center w-80 h-80 font-[600] text-white rounded-16 bg-main-two-600 text-28">00</span>
                                            <span class="mt-8 text-neutral-600 text-xl text-uppercase font-[500] block text-center">Days</span>
                                        </li>
                                        <li><span id="hours" class="flex items-center justify-center w-80 h-80 font-[600] text-white rounded-16 bg-main-two-600 text-28">00</span>
                                            <span class="mt-8 text-neutral-600 text-xl text-uppercase font-[500] block text-center">Hour</span>
                                        </li>
                                        <li><span id="minutes" class="flex items-center justify-center w-80 h-80 font-[600] text-white rounded-16 bg-main-two-600 text-28">00</span>
                                            <span class="mt-8 text-neutral-600 text-xl text-uppercase font-[500] block text-center">Min</span>
                                        </li>
                                        <li><span id="seconds" class="flex items-center justify-center w-80 h-80 font-[600] text-white rounded-16 bg-main-two-600 text-28">00</span>
                                            <span class="mt-8 text-neutral-600 text-xl text-uppercase font-[500] block text-center">Sec</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // ✅ شمارش معکوس
        if (discountEnd) {
            const countdown = setInterval(() => {
                const now = new Date().getTime();
                const distance = discountEnd - now;

                if (distance < 0) {
                    clearInterval(countdown);
                    document.getElementById("countdown24").innerHTML = "<p class='text-red-500 text-lg'>Discount has ended.</p>";
                    return;
                }

                const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                document.getElementById("days").textContent = days.toString().padStart(2, "0");
                document.getElementById("hours").textContent = hours.toString().padStart(2, "0");
                document.getElementById("minutes").textContent = minutes.toString().padStart(2, "0");
                document.getElementById("seconds").textContent = seconds.toString().padStart(2, "0");
            }, 1000);
        }
    } catch (error) {
        console.error("Error loading Deal of the Day:", error);
        dealContainer.innerHTML = "<p class='text-center text-white py-5'>خطا در بارگذاری تخفیف روز.</p>";
    }
});




function renderProductImages(imageList = []) {
    console.log(imageList);
    
  const container = document.getElementById("productImagesContainer");
  if (!container) return;

  // اگر هیچ تصویری نیامده، از عکس‌های پیش‌فرض استفاده کن
  const defaultImages = [
    "images/product-details-two-thumb1.png",
    "images/product-details-two-thumb2.png",
    "images/product-details-two-thumb3.png"
  ];
  const images = imageList.length > 0 ? imageList : defaultImages;

  // HTML ساختار ثابت
  container.innerHTML = `
    <div class="product-details__left text-center">
      <!-- تصویر اصلی -->
      <div id="mainImage" class="border border-gray-200 rounded-2xl overflow-hidden mb-4">
        <img id="mainImageSrc" src="${images[0]}" alt="Product"
          class="w-full h-auto object-contain">
      </div>

      <!-- تصاویر کوچک -->
      <div id="thumbnailContainer" class="flex flex-wrap justify-center gap-3"></div>
    </div>
  `;

  const mainImage = container.querySelector("#mainImageSrc");
  const thumbnailContainer = container.querySelector("#thumbnailContainer");

  // ساخت تصاویر کوچک به صورت داینامیک
  images.forEach((img, index) => {
    const thumb = document.createElement("img");
    thumb.src = img;
    thumb.alt = `Product ${index + 1}`;
    thumb.className =
      "thumb-img border border-gray-200 rounded-xl w-20 h-20 p-2 cursor-pointer object-contain transition-transform duration-200 hover:scale-105";

    thumb.addEventListener("click", () => {
      mainImage.src = img;
      container.querySelectorAll(".thumb-img").forEach(t => t.classList.remove("ring-2", "ring-blue-400"));
      thumb.classList.add("ring-2", "ring-blue-400");
    });

    thumbnailContainer.appendChild(thumb);
  });

  // انتخاب اولین عکس به‌صورت پیش‌فرض
  const firstThumb = container.querySelector(".thumb-img");
  if (firstThumb) firstThumb.classList.add("ring-2", "ring-blue-400");
}








