<?php
require_once("db_config.php");

// Fetch news items
$result = $conn->query("SELECT * FROM news ORDER BY created_at DESC");
$news_items = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

// Fetch section title - wrapped in try-catch for safety
$section_title = '';
$section_description = '';
try {
    $settingsRes = @$conn->query("SELECT section_title, section_description FROM news_settings LIMIT 1");
    if ($settingsRes && $row = $settingsRes->fetch_assoc()) {
        $section_title = $row['section_title'] ?? '';
        $section_description = $row['section_description'] ?? '';
    }
} catch (Exception $e) {
    // Table doesn't exist yet, that's fine - will create on first admin save
}

// Calculate responsive layout
$itemCount = count($news_items);
$layout = 'single'; // single (1), double (2), carousel (3+)

if ($itemCount === 2) {
    $layout = 'double';
} elseif ($itemCount >= 3) {
    $layout = 'carousel';
}
?>

<div class="news-slider-wrapper" data-item-count="<?php echo $itemCount; ?>" data-layout="<?php echo $layout; ?>">
    <!-- Section Title -->
    <?php if ($itemCount > 0): ?>
        <div class="news-section-header">
            <?php if ($section_title): ?>
                <h2 class="news-section-title"><?php echo htmlspecialchars($section_title); ?></h2>
            <?php endif; ?>
            <?php if ($section_description): ?>
                <p class="news-section-description"><?php echo htmlspecialchars($section_description); ?></p>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="news-slider" data-layout="<?php echo $layout; ?>">
        <?php if (!empty($news_items)): ?>
            <!-- Navigation Buttons (show for carousel with 3+ items) -->
            <?php if ($layout === 'carousel' && $itemCount >= 3): ?>
                <button class="slider-btn prev" aria-label="Previous">‹</button>
                <button class="slider-btn next" aria-label="Next">›</button>
            <?php endif; ?>

            <div class="slider-wrapper">
                <div class="slider-container">
                    <?php foreach($news_items as $row): 
                        $displayType = isset($row['display_type']) ? $row['display_type'] : 'full';
                    ?>
                        <div class="news-item display-type-<?php echo htmlspecialchars($displayType); ?> <?php echo $row['is_sale'] ? 'sale' : ''; ?>" data-display-type="<?php echo htmlspecialchars($displayType); ?>">
                            
                            <?php if ($displayType === 'image_only'): ?>
                                <!-- Image Only Layout -->
                                <?php if($row['image']): ?>
                                    <div class="news-image-container full-width">
                                        <img src="<?php echo htmlspecialchars($row['image']); ?>" alt="<?php echo htmlspecialchars($row['title']); ?>">
                                    </div>
                                <?php endif; ?>
                                
                            <?php elseif ($displayType === 'description_only'): ?>
                                <!-- Title & Description Only Layout -->
                                <div class="news-content full-width">
                                    <h3><?php echo htmlspecialchars($row['title']); ?></h3>
                                    <?php if($row['description']): ?>
                                        <p><?php echo htmlspecialchars($row['description']); ?></p>
                                    <?php endif; ?>
                                    <div class="news-footer">
                                        <?php if(!empty($row['is_sale'])): ?>
                                            <span class="sale-badge">🔥 Sale Highlight</span>
                                        <?php endif; ?>
                                        <?php if(isset($row['has_shop_button']) && $row['has_shop_button']): ?>
                                            <a href="<?php echo htmlspecialchars(isset($row['shop_link']) ? $row['shop_link'] : '#'); ?>" class="shop-btn">Shop Now</a>
                                        <?php endif; ?>
                                    </div>
                                </div>

                            <?php elseif ($displayType === 'title_only'): ?>
                                <!-- Title Only Layout -->
                                <div class="news-content minimal">
                                    <h3><?php echo htmlspecialchars($row['title']); ?></h3>
                                </div>

                            <?php elseif ($displayType === 'banner_only'): ?>
                                <!-- Banner Mode Layout -->
                                <div class="news-item-banner">
                                    <?php if($row['image']): ?>
                                        <div class="news-image-container">
                                            <img src="<?php echo htmlspecialchars($row['image']); ?>" alt="<?php echo htmlspecialchars($row['title']); ?>">
                                        </div>
                                    <?php endif; ?>
                                    <div class="banner-overlay">
                                        <h3><?php echo htmlspecialchars($row['title']); ?></h3>
                                        <?php if(isset($row['has_shop_button']) && $row['has_shop_button']): ?>
                                            <a href="<?php echo htmlspecialchars(isset($row['shop_link']) ? $row['shop_link'] : '#'); ?>" class="shop-btn">Shop Now</a>
                                        <?php endif; ?>
                                    </div>
                                </div>

                            <?php else: // 'full' or default - Both Title & Image ?>
                                <!-- Full Layout (Title & Image, Half/Half) -->
                                <div class="news-item-hybrid">
                                    <?php if($row['image']): ?>
                                        <div class="news-image-container half-width">
                                            <img src="<?php echo htmlspecialchars($row['image']); ?>" alt="<?php echo htmlspecialchars($row['title']); ?>">
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="news-content <?php echo !$row['image'] ? 'full-width' : 'half-width'; ?>">
                                        <h3><?php echo htmlspecialchars($row['title']); ?></h3>
                                        <?php if($row['description']): ?>
                                            <p><?php echo htmlspecialchars($row['description']); ?></p>
                                        <?php endif; ?>
                                        <div class="news-footer">
                                            <?php if(!empty($row['is_sale'])): ?>
                                                <span class="sale-badge">🔥 Sale Highlight</span>
                                            <?php endif; ?>
                                            <?php if(isset($row['has_shop_button']) && $row['has_shop_button']): ?>
                                                <a href="<?php echo htmlspecialchars(isset($row['shop_link']) ? $row['shop_link'] : '#'); ?>" class="shop-btn">Shop Now</a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php else: ?>
            <div class="no-news">
                <p>No news items to display</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
/* Main Section Wrapper */
.news-slider-wrapper {
    width: 100%;
}

/* Section Header */
.news-section-header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px;
    animation: slideDown 0.6s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.news-section-title {
    font-size: 2.2em;
    color: #2c3e50;
    margin-bottom: 10px;
    font-weight: 700;
    letter-spacing: -0.5px;
}

.news-section-description {
    font-size: 1.1em;
    color: #666;
    max-width: 600px;
    margin: 0 auto;
    line-height: 1.5;
}

/* Main Slider Container */
.news-slider {
    position: relative;
    overflow: hidden;
    width: 100%;
    background: linear-gradient(135deg, #f59663 0%, #ef6f9e 100%);
    padding: 20px;
    margin: 0;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* Slider Wrapper */
.slider-wrapper {
    position: relative;
    overflow: hidden;
    width: 100%;
}

.slider-container {
    display: flex;
    transition: transform 0.6s cubic-bezier(0.4, 0.0, 0.2, 1);
    will-change: transform;
    gap: 15px;
}

/* News Item Base Styles */
.news-item {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    padding: 0;
    margin: 0;
}

.news-item:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    transform: translateY(-4px);
}

/* Responsive Layouts */
/* Single Item Layout */
[data-layout="single"] .news-item {
    flex: 0 0 100%;
    min-height: 250px;
}

/* Double Item Layout */
[data-layout="double"] .news-item {
    flex: 0 0 calc(50% - 8px);
    min-height: 320px;
}

/* Carousel Layout (3+ items) - Show 2 items per view */
[data-layout="carousel"] .news-item {
    flex: 0 0 calc(50% - 8px);
    min-height: 300px;
}

/* Display Type Specific Layouts */
.news-item-hybrid {
    display: flex;
    height: 100%;
    flex-direction: row;
    background: linear-gradient(135deg, #f1ec8a 0%, #f1abbd 100%);
}

.news-item-banner {
    position: relative;
    min-height: 300px;
    display: flex;
    align-items: flex-end;
}

/* Image Containers */
.news-image-container {
    background: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.news-image-container.full-width {
    width: 100%;
    height: 100%;
    min-height: 300px;
}

.news-image-container.half-width {
    width: 50%;
    height: 100%;
    min-height: 200px;
}

.news-item-banner .news-image-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
}

.news-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    display: block;
    transition: transform 0.3s ease, filter 0.3s ease;
}
.news-item img:hover {
    transform: scale(1.05);
    filter: brightness(1.1);
}

/* Ensure image-only display type fills entire item */
.display-type-image_only {
    display: flex;
    align-items: stretch;
    justify-content: stretch;
    overflow: hidden;
    min-height: 250px !important;
    height: 100% !important;
}

.display-type-image_only .news-image-container {
    width: 100% !important;
    height: 100% !important;
    flex: 1 1 100%;
}

.display-type-image_only .news-image-container img {
    width: 100% !important;
    height: 100% !important;
}

/* Hide any text content in image-only items */
.display-type-image_only .news-content,
.display-type-image_only h3,
.display-type-image_only p,
.display-type-image_only .news-footer {
    display: none !important;
}

/* Content Sections */
.news-content {
    padding: 18px;
    display: flex;
    flex-direction: column;
    /* justify-content: space-between; */
    background: linear-gradient(135deg, <?php echo $bgStart; ?> 0%, <?php echo $bgEnd; ?> 100%);
}

.news-content.full-width {
    width: 100%;
}

.news-content.half-width {
    width: 50%;
    flex-grow: 1;
}

.news-content.minimal {
    justify-content: center;
    text-align: center;
    min-height: 200px;
}

.news-content h3 {
    color: #2c3e50;
    margin: 0 0 12px 0;
    font-size: 1.15em;
    line-height: 1.3;
    word-break: break-word;
    font-weight: 600;
}

.news-content.minimal h3 {
    font-size: 1.5em;
    margin-bottom: 0;
}

.news-content p {
    color: #666;
    margin: 0 0 12px 0;
    font-size: 0.9em;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.news-content.minimal p {
    display: none;
}

.news-footer {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
    margin-top: 12px;
}

/* Banner Overlay */
.banner-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(to top, rgba(0, 0, 0, 0.85), transparent);
    padding: 40px 20px 20px;
    z-index: 2;
    color: white;
    text-align: center;
}

.banner-overlay h3 {
    color: white;
    margin: 0 0 12px 0;
    font-size: 1.4em;
    font-weight: 700;
    line-height: 1.2;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
}

/* Sale Badge - Keep border but no fixed height */
.news-item.sale {
    border: 3px solid #ff6b6b;
}

.sale-badge {
    display: inline-block;
    background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%);
    color: white;
    padding: 6px 13px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 0.85em;
    animation: float 3s ease-in-out infinite;
    box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

@keyframes float {
    0%, 100% { transform: translateY(0px); }
    50% { transform: translateY(-6px); }
}

/* Shop Button */
.shop-btn {
    display: inline-block;
    background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
    color: white;
    padding: 10px 22px;
    border-radius: 20px;
    text-decoration: none;
    font-weight: 600;
    font-size: 0.9em;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

.shop-btn:hover {
    background: linear-gradient(135deg, #f57c00 0%, #e65100 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(255, 152, 0, 0.4);
}

.shop-btn:active {
    transform: translateY(0px);
}

/* Navigation Buttons */
.slider-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(0, 0, 0, 0.6);
    color: white;
    border: none;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    font-size: 30px;
    cursor: pointer;
    transition: all 0.3s ease;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    line-height: 1;
}

.slider-btn:hover {
    background: rgba(0, 0, 0, 0.9);
    transform: translateY(-50%) scale(1.15);
}

.slider-btn:active {
    transform: translateY(-50%) scale(0.95);
}

.slider-btn.prev {
    left: 20px;
}

.slider-btn.next {
    right: 20px;
}

/* No News State */
.no-news {
    padding: 80px 20px;
    text-align: center;
    color: #999;
    font-size: 1.2em;
    font-weight: 500;
}

/* Responsive Design */
@media (max-width: 1024px) {
    [data-layout="carousel"] .news-item {
        flex: 0 0 calc(100% - 8px);
    }

    .news-section-title {
        font-size: 1.8em;
    }
}

@media (max-width: 768px) {
    [data-layout="double"] .news-item,
    [data-layout="carousel"] .news-item {
        flex: 0 0 100%;
        min-height: 280px;
    }

    .news-item-hybrid {
        flex-direction: column;
    }

    .news-image-container.half-width {
        width: 100%;
        height: 180px;
    }

    .news-content.half-width {

        width: 100%;
    }

    .news-section-header {
        margin-bottom: 20px;
        padding: 15px;
    }

    .news-section-title {
        font-size: 1.5em;
        margin-bottom: 8px;
    }

    .news-section-description {
        font-size: 0.95em;
    }

    .news-item {
        min-height: auto;
    }

    .slider-btn {
        width: 44px;
        height: 44px;
        font-size: 24px;
    }

    .slider-btn.prev { left: 12px; }
    .slider-btn.next { right: 12px; }

    .news-content {
        padding: 14px;
    }

    .news-content h3 {
        font-size: 1em;
        margin-bottom: 8px;
    }

    .news-content p {
        font-size: 0.85em;
        margin-bottom: 8px;
    }

    .shop-btn {
        padding: 8px 16px;
        font-size: 0.85em;
    }

    .banner-overlay {
        padding: 30px 15px 15px;
    }

    .banner-overlay h3 {
        font-size: 1.1em;
    }
}

@media (max-width: 480px) {
    [data-layout="single"] .news-item,
    [data-layout="double"] .news-item,
    [data-layout="carousel"] .news-item {
        flex: 0 0 100%;
        min-height: auto;
    }

    .news-slider {
        padding: 12px;
    }

    .slider-container {
        gap: 10px;
    }

    .news-image-container.full-width {
        min-height: 200px;
    }

    .news-image-container.half-width {
        height: 150px;
    }

    .news-item-banner {
        min-height: 220px;
    }

    .news-section-header {
        padding: 12px;
        margin-bottom: 15px;
    }

    .news-section-title {
        font-size: 1.3em;
        margin-bottom: 6px;
    }

    .news-section-description {
        font-size: 0.9em;
    }

    .news-content {
        padding: 12px;
    }

    .news-content h3 {
        font-size: 0.95em;
        margin-bottom: 6px;
    }

    .news-content p {
        font-size: 0.8em;
        margin-bottom: 6px;
        -webkit-line-clamp: 1;
    }

    .news-footer {
        gap: 6px;
        margin-top: 8px;
    }

    .sale-badge {
        padding: 4px 10px;
        font-size: 0.75em;
    }

    .shop-btn {
        padding: 7px 14px;
        font-size: 0.8em;
    }

    .slider-btn {
        width: 38px;
        height: 38px;
        font-size: 20px;
    }

    .slider-btn.prev { left: 8px; }
    .slider-btn.next { right: 8px; }

    .banner-overlay {
        padding: 20px 10px 10px;
    }

    .banner-overlay h3 {
        font-size: 0.95em;
        margin-bottom: 8px;
    }
}

/* Smooth scrollbar */
::-webkit-scrollbar {
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb {
    background: #ff9800;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background: #f57c00;
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const wrapper = document.querySelector('.slider-wrapper');
    const container = document.querySelector('.slider-container');
    const items = document.querySelectorAll('.news-item');
    const slider = document.querySelector('.news-slider');
    const nextBtn = document.querySelector('.news-slider .next');
    const prevBtn = document.querySelector('.news-slider .prev');
    const layout = slider ? slider.getAttribute('data-layout') : 'single';

    if (!wrapper || !container || items.length === 0) return;

    let currentIndex = 0;
    let itemsToShowPerView = 1;
    let autoplayTimer;
    
    // Only enable carousel functionality for 3+ items
    const isCarousel = layout === 'carousel';

    // Determine items per view based on screen size (for carousel mode)
    function updateItemsPerView() {
        if (!isCarousel) {
            itemsToShowPerView = items.length;
            return;
        }

        if (window.innerWidth >= 1024) {
            itemsToShowPerView = 2;  // 2 items per view on desktop
        } else if (window.innerWidth >= 768) {
            itemsToShowPerView = 1;  // 1 item per view on tablet
        } else {
            itemsToShowPerView = 1;  // 1 item per view on mobile
        }
    }

    // Calculate item width
    function getItemWidth() {
        return wrapper.clientWidth / itemsToShowPerView;
    }

    // Update slider position
    function updateSlider() {
        const itemWidth = getItemWidth();
        const offset = currentIndex * itemWidth;
        container.style.transform = `translateX(-${offset}px)`;
    }

    // Go to next item (carousel only)
    function goToNext() {
        if (!isCarousel) return;
        const maxIndex = Math.max(0, items.length - itemsToShowPerView);
        currentIndex = currentIndex >= maxIndex ? 0 : currentIndex + 1;
        updateSlider();
        resetAutoplay();
    }

    // Go to previous item (carousel only)
    function goToPrev() {
        if (!isCarousel) return;
        currentIndex = currentIndex <= 0 ? Math.max(0, items.length - itemsToShowPerView) : currentIndex - 1;
        updateSlider();
        resetAutoplay();
    }

    // Autoplay functionality (carousel only)
    function startAutoplay() {
        if (!isCarousel) return;
        autoplayTimer = setInterval(goToNext, 6000);
    }

    function resetAutoplay() {
        clearInterval(autoplayTimer);
        startAutoplay();
    }

    // Event listeners
    if (isCarousel && nextBtn) nextBtn.addEventListener('click', goToNext);
    if (isCarousel && prevBtn) prevBtn.addEventListener('click', goToPrev);

    // Touch support for mobile (carousel only)
    let touchStartX = 0;
    let touchEndX = 0;

    container.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;
    }, false);

    container.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;
        if (isCarousel) handleSwipe();
    }, false);

    function handleSwipe() {
        if (touchStartX - touchEndX > 50) {
            goToNext();
        } else if (touchEndX - touchStartX > 50) {
            goToPrev();
        }
    }

    // Pause autoplay on hover (carousel only)
    if (isCarousel) {
        wrapper.addEventListener('mouseenter', () => clearInterval(autoplayTimer));
        wrapper.addEventListener('mouseleave', startAutoplay);
    }

    // Handle window resize
    window.addEventListener('resize', () => {
        updateItemsPerView();
        updateSlider();
    });

    // Initialize
    updateItemsPerView();
    updateSlider();
    if (isCarousel) startAutoplay();
});
</script>
