<?php
require 'components/db_connect.php';

$banners = [];

try {
    if ($conn instanceof PDO) {
        $stmt = $conn->query("SELECT * FROM banners ORDER BY sort_order ASC");
        $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($conn instanceof mysqli) {
        $result = $conn->query("SELECT * FROM banners ORDER BY created_at DESC");
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $banners[] = $row;
            }
        }
    } else {
        throw new Exception("Unsupported database connection type.");
    }
} catch (Exception $e) {
    $banners = [];
}
?>

<?php if (!empty($banners)) { ?>
    <div class="banner-slider container-banner">
        <div class="banner-slides">
            <?php foreach ($banners as $index => $banner) { ?>
                <div class="banner-slide <?php echo $index === 0 ? 'active' : ''; ?>">
                    <?php if (!empty($banner['link_url'])) { ?>
                        <a href="<?php echo htmlspecialchars($banner['link_url']); ?>" target="_blank" rel="noopener noreferrer">
                            <img src="/Uploads/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" alt="Banner <?php echo $index + 1; ?>">
                        </a>
                    <?php } else { ?>
                        <img src="/Uploads/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" alt="Banner <?php echo $index + 1; ?>">
                    <?php } ?>
                </div>
            <?php } ?>
        </div>

        <button class="banner-prev">&#10094;</button>
        <button class="banner-next">&#10095;</button>

        <div class="banner-dots">
            <?php foreach ($banners as $index => $banner) { ?>
                <span class="banner-dot <?php echo $index === 0 ? 'active' : ''; ?>" data-index="<?php echo $index; ?>"></span>
            <?php } ?>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const slides = document.querySelectorAll('.banner-slide');
        const dots = document.querySelectorAll('.banner-dot');
        const prevButton = document.querySelector('.banner-prev');
        const nextButton = document.querySelector('.banner-next');
        let currentIndex = 0;
        let autoSlide;

        // Swipe variables
        let touchStartX = 0;
        let touchEndX = 0;

        function updateSlider(index) {
            slides.forEach((slide, i) => {
                slide.classList.toggle('active', i === index);
            });
            dots.forEach((dot, i) => {
                dot.classList.toggle('active', i === index);
            });
            currentIndex = index;
        }

        function nextSlide() {
            currentIndex = (currentIndex + 1) % slides.length;
            updateSlider(currentIndex);
            resetAutoSlide();
        }

        function prevSlide() {
            currentIndex = (currentIndex - 1 + slides.length) % slides.length;
            updateSlider(currentIndex);
            resetAutoSlide();
        }

        function startAutoSlide() {
            autoSlide = setInterval(() => {
                nextSlide();
            }, 5000);
        }

        function resetAutoSlide() {
            clearInterval(autoSlide);
            startAutoSlide();
        }

        // Dot click
        dots.forEach((dot, i) => {
            dot.addEventListener('click', () => {
                updateSlider(i);
                resetAutoSlide();
            });
        });

        // Prev/Next buttons
        prevButton.addEventListener('click', prevSlide);
        nextButton.addEventListener('click', nextSlide);

        // Swipe support
        const sliderContainer = document.querySelector('.banner-slider');
        sliderContainer.addEventListener('touchstart', e => {
            touchStartX = e.changedTouches[0].screenX;
        });
        sliderContainer.addEventListener('touchend', e => {
            touchEndX = e.changedTouches[0].screenX;
            if (touchEndX < touchStartX - 40) nextSlide(); // swipe left
            if (touchEndX > touchStartX + 40) prevSlide(); // swipe right
        });

        // Initialize first slide
        updateSlider(currentIndex);
        startAutoSlide();
    });
    </script>
<?php } ?>
