document.addEventListener("DOMContentLoaded", () => {
    const sliderContainer = document.getElementById("slider-container");
    const apiUrl = "controlls/api/slider.php";

    fetch(apiUrl)
        .then(res => res.json())
        .then(data => {
            if (!Array.isArray(data) || data.length === 0) {
                sliderContainer.innerHTML = "<p>هیچ اسلایدی یافت نشد.</p>";
                return;
            }

            data.forEach(item => {
                const slide = document.createElement("div");
                slide.className = "slide";
                slide.style.backgroundColor = item.color || "#333";

                slide.innerHTML = `
                    <div class="row items-center g-4">
                        <div class="xl:w-6/12 flex-grow-0 flex-shrink-0 basis-auto">
                            <div class="span3">
                                <span class="text-white mb-8 h6">UP TO ${item.discount_value}% OFF</span>
                                <h1 class="text-white display-one">${item.title}</h1>
                                <p class="text-white max-w-472 text-2xl">${item.description}</p>
                                ${item.discount_code ? `<strong>Discount code: ${item.discount_code}</strong>` : ''}
                            </div>
                        </div>
                        <div class="xl:w-6/12 flex-grow-0 flex-shrink-0 basis-auto">
                            <div class="flex justify-center">
                                <img src="controlls/uploads/${item.image}" alt="${item.title}">
                            </div>
                        </div>
                    </div>
                `;

                sliderContainer.appendChild(slide);
            });

            // initialize slick slider
            if (typeof $ !== "undefined" && $(sliderContainer).slick) {
                $(sliderContainer).slick({
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    arrows: true,
                    prevArrow: '#banner-three-prev',
                    nextArrow: '#banner-three-next',
                    autoplay: true,
                    autoplaySpeed: 5000,
                });
            }
        })
        .catch(err => {
            console.error("خطا در دریافت اسلایدر:", err);
            sliderContainer.innerHTML = "<p>خطا در بارگذاری اسلایدر.</p>";
        });
});
