<?php
require_once 'config/database.php';
require_once 'includes/visitor_counter.php';
require_once 'includes/url_helper.php';
require_once 'includes/youtube_helper.php';

// Function to get YouTube video ID from URL
function getYouTubeId($url) {
    $pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/';
    preg_match($pattern, $url, $matches);
    return isset($matches[1]) ? $matches[1] : '';
}

// Set page variables
$current_page = 'index';
$page_title = 'BBWS Cilicis - Balai Besar Wilayah Sungai Ciliwung Cisadane';

// Get data from database
$pdo = getConnection();

// Get all active berita
$stmt = $pdo->prepare("SELECT * FROM berita WHERE status = 'aktif' ORDER BY COALESCE(tanggal_publikasi, created_at) DESC");
$stmt->execute();
$berita = $stmt->fetchAll();

// Get latest galeri infrastruktur
$stmt = $pdo->prepare("SELECT * FROM galeri_infrastruktur WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 8");
$stmt->execute();
$galeri_infrastruktur = $stmt->fetchAll();

// Get latest galeri kegiatan
$stmt = $pdo->prepare("SELECT * FROM galeri_kegiatan WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 4");
$stmt->execute();
$galeri_kegiatan = $stmt->fetchAll();

// Get infrastructure gallery (up to 4) for the slider
$galeri_slider = array_slice($galeri_infrastruktur, 0, 4);

    // Get latest videos
    try {
        $stmt = $pdo->prepare("SELECT * FROM video WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 4");
        $stmt->execute();
        $videos = $stmt->fetchAll();
    } catch (PDOException $e) {
        $videos = [];
    }

// Get latest majalah
$stmt = $pdo->prepare("SELECT * FROM majalah WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 4");
$stmt->execute();
$majalah = $stmt->fetchAll();

// Get latest pengumuman
$stmt = $pdo->prepare("SELECT * FROM pengumuman WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 4");
$stmt->execute();
$pengumuman_sidebar = $stmt->fetchAll();

// Debug: Check if pengumuman data exists
if (empty($pengumuman_sidebar)) {
    // If no pengumuman, try to get from majalah table as fallback
    $stmt = $pdo->prepare("SELECT * FROM majalah WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 4");
    $stmt->execute();
    $pengumuman_sidebar = $stmt->fetchAll();
}

// Get latest infografis
$stmt = $pdo->prepare("SELECT * FROM infografis WHERE status = 'aktif' ORDER BY created_at DESC LIMIT 6");
$stmt->execute();
$infografis = $stmt->fetchAll();

// Fix path duplication issue for infografis (same as sidebar-data.php)
foreach ($infografis as &$item) {
    if (isset($item['gambar'])) {
        // Use getFullUrl instead of getUploadUrl to avoid duplication
        $item['gambar_url'] = getFullUrl($item['gambar']);
    }
}

// Get active banners for slider
$stmt = $pdo->prepare("SELECT * FROM banner WHERE status = 'aktif' ORDER BY urutan ASC, created_at DESC");
$stmt->execute();
$banners = $stmt->fetchAll();

// Get visitor statistics
$visitorCounter = new VisitorCounter();
$stats = $visitorCounter->getStats();

// Include header
include 'includes/header.php';
?>
<!-- Swiper CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"/>
<!-- Custom CSS -->
<link rel="stylesheet" href="assets/css/index.css"/>


<!-- Swiper JS -->
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<!-- Custom JavaScript -->
<script src="assets/js/index.js"></script>

<!-- Custom Banner Slider JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const slider = document.getElementById('bannerSlider');
    if (!slider) return;
    
    const track = document.getElementById('bannerSliderTrack');
    const slides = track.querySelectorAll('.slider-slide');
    const prevBtn = document.getElementById('bannerPrev');
    const nextBtn = document.getElementById('bannerNext');
    const dots = slider.querySelectorAll('.dot');
    
    let currentSlide = 0;
    let autoSlideInterval;
    
    // Function to show specific slide
    function showSlide(index) {
        console.log('Showing slide:', index);
        // Remove active class from all slides and dots
        slides.forEach(slide => slide.classList.remove('active'));
        dots.forEach(dot => dot.classList.remove('active'));
        
        // Add active class to current slide and dot
        if (slides[index]) {
            slides[index].classList.add('active');
            console.log('Slide', index, 'activated');
        }
        if (dots[index]) {
            dots[index].classList.add('active');
        }
        
        currentSlide = index;
    }
    
    // Function to go to next slide
    function nextSlide() {
        console.log('Moving to next slide, current:', currentSlide);
        const nextIndex = (currentSlide + 1) % slides.length;
        showSlide(nextIndex);
    }
    
    // Function to go to previous slide
    function prevSlide() {
        const prevIndex = (currentSlide - 1 + slides.length) % slides.length;
        showSlide(prevIndex);
    }
    
    // Auto slide function
    function startAutoSlide() {
        console.log('Starting auto slide interval');
        autoSlideInterval = setInterval(nextSlide, 8000);
    }
    
    function stopAutoSlide() {
        console.log('Stopping auto slide interval');
        clearInterval(autoSlideInterval);
    }
    
    // Event listeners
    if (nextBtn) {
        nextBtn.addEventListener('click', function() {
            stopAutoSlide();
            nextSlide();
            startAutoSlide();
        });
    }
    
    if (prevBtn) {
        prevBtn.addEventListener('click', function() {
            stopAutoSlide();
            prevSlide();
            startAutoSlide();
        });
    }
    
    // Dot navigation
    dots.forEach((dot, index) => {
        dot.addEventListener('click', function() {
            stopAutoSlide();
            showSlide(index);
            startAutoSlide();
        });
    });
    
    // Pause on hover
    slider.addEventListener('mouseenter', stopAutoSlide);
    slider.addEventListener('mouseleave', startAutoSlide);
    
    // Start auto slide
    console.log('Slider elements found:', {
        slider: !!slider,
        track: !!track,
        slides: slides.length,
        prevBtn: !!prevBtn,
        nextBtn: !!nextBtn,
        dots: dots.length
    });
    
    if (slides.length > 1) {
        console.log('Starting auto slide with', slides.length, 'slides');
        startAutoSlide();
    } else {
        console.log('Only 1 slide found, auto slide disabled');
    }
});
</script>

    <!-- Main Layout dengan Sidebar Kiri -->
    <section class="py-4">
        <div class="container-fluid" style="padding: 15px 150px 100px; margin-top: -12px;">
            <div class="row g-4">
                <!-- Left Sidebar -->
                <?php include 'includes/sidebar-left.php'; ?>

                <!-- Center Content -->
                <div class="col-lg-6 col-md-12 col-sm-12 order-lg-2 order-2">
                    <!-- Hero Banner Slider -->
                    <div class="card border-0 shadow-sm mb-2" style="border-radius: 5px;">
                        <?php if (!empty($banners)): ?>
                            <div class="custom-banner-slider" id="bannerSlider">
                                <div class="slider-container">
                                    <div class="slider-track" id="bannerSliderTrack">
                                        <?php foreach ($banners as $index => $banner): ?>
                                            <div class="slider-slide <?= $index === 0 ? 'active' : '' ?>">
                                                <img src="<?= htmlspecialchars($banner['gambar']) ?>" 
                                                     alt="<?= htmlspecialchars($banner['judul']) ?>"
                                                     class="slider-image">
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php if (count($banners) > 1): ?>
                                    <button class="slider-btn slider-prev" id="bannerPrev">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <button class="slider-btn slider-next" id="bannerNext">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                    <div class="slider-dots">
                                        <?php foreach ($banners as $index => $banner): ?>
                                            <span class="dot <?= $index === 0 ? 'active' : '' ?>" data-slide="<?= $index ?>"></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                        <?php endif; ?>
                    </div>

                    <!-- Berita Section -->
                    <div class="berita-section">
                        <div class="berita-header">
                            <h6 class="berita-title-header fw-bold">
                                Berita Terkini
                            </h6>
                        </div>
                        <?php if (!empty($berita)): ?>
                            <!-- Berita Slider -->
                            <div class="berita-slider-container">
                                <div class="berita-slider-wrapper">
                                    <!-- Navigation Arrows -->
                                    <button class="berita-nav-btn berita-prev" id="beritaPrev">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <button class="berita-nav-btn berita-next" id="beritaNext">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                    
                                    <!-- Slider Track -->
                                    <div class="berita-slider-track" id="beritaSliderTrack">
                                        <?php foreach ($berita as $item): ?>
                                            <div class="berita-slide">
                                                <div class="berita-card">
                                                    <div class="berita-img-wrap">
                                                        <?php if ($item['gambar']): ?>
                                                            <?php 
                                                            $image_path = $item['gambar'];
                                                            if (strpos($image_path, 'uploads/berita/') !== 0) {
                                                                $image_path = 'uploads/berita/' . $image_path;
                                                            }
                                                            ?>
                                                            <img src="<?php echo htmlspecialchars($image_path); ?>" 
                                                                 alt="<?php echo htmlspecialchars($item['judul']); ?>">
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="berita-overlay">
                                                        <h4 class="berita-title">
                                                            <a href="<?php echo getBeritaUrl($item['id'], $item['judul'], $item['kategori']); ?>">
                                                                <?php echo htmlspecialchars($item['judul']); ?>
                                                            </a>
                                                        </h4>
                                                        <div class="berita-meta">
                                                            <span>
                                                                <?php 
                                                                // Gunakan tanggal_publikasi jika ada, jika tidak gunakan created_at
                                                                $tanggal_tampil = !empty($item['tanggal_publikasi']) ? $item['tanggal_publikasi'] : $item['created_at'];
                                                                echo date('Y-m-d', strtotime($tanggal_tampil)); 
                                                                ?>
                                                            </span>
                                                        </div>
                                                        <p class="berita-desc">
                                                            <?php 
                                                                $excerpt = strip_tags($item['konten']);
                                                                $excerpt = trim($excerpt);
                                                                if (strlen($excerpt) > 120) {
                                                                    $excerpt = substr($excerpt, 0, 120) . '...';
                                                                }
                                                                echo htmlspecialchars($excerpt);
                                                            ?>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <p class="text-muted text-center">Belum ada berita.</p>
                        <?php endif; ?>
                    </div>
        
        <!-- Card Berita Tambahan (Seperti pada gambar) -->
        <div class="card mb-2">
        <div class="berita-header">
                            <h6 class="berita-title-header fw-bold">
                                Berita
                            </h6>
                        </div>
            
            <div class="news-slider-container">
                <div class="news-slider-wrapper">
                    <div class="news-slider" id="beritaSlider">
                <?php 
                // Mengambil 10 berita pertama untuk ditampilkan sebagai card
                $berita_cards = array_slice($berita, 0, 10);
                if (!empty($berita_cards)): 
                    foreach ($berita_cards as $item): 
                        // Potong judul jika terlalu panjang (maksimal 50 karakter)
                        $judul = htmlspecialchars($item['judul']);
                        if (strlen($judul) > 50) {
                            $judul = substr($judul, 0, 50) . '...';
                        }
                        
                        // Format tanggal seperti pada gambar
                        $tanggal_tampil = !empty($item['tanggal_publikasi']) ? $item['tanggal_publikasi'] : $item['created_at'];
                        $tanggal = date('d/m/Y', strtotime($tanggal_tampil));
                        
                        // Potong ringkasan (maksimal 80 karakter)
                        $ringkasan = strip_tags($item['konten']);
                        $ringkasan = trim($ringkasan);
                        if (strlen($ringkasan) > 50) {
                            $ringkasan = substr($ringkasan, 0, 50) . '...';
                        }
                        $ringkasan = htmlspecialchars($ringkasan);
                        
                        // Path gambar
                        $image_path = $item['gambar'];
                        if (!empty($image_path) && strpos($image_path, 'uploads/berita/') !== 0) { 
                            $image_path = 'uploads/berita/' . $image_path; 
                        }
                        if (empty($image_path)) {
                            $image_path = 'assets/img/default-news.jpg'; // Gambar default jika tidak ada
                        }
                ?>
                    <div class="col-6 col-md-4 col-lg-2-4">
                        <a href="<?php echo getBeritaUrl($item['id'], $item['judul'], $item['kategori']); ?>" class="text-decoration-none">
                            <div class="card berita-card-custom">
                                <div class="card-img-container">
                                    <img src="<?php echo htmlspecialchars($image_path); ?>" class="card-img-top" alt="<?php echo $judul; ?>">
                                </div>
                                <div class="card-body p-1">
                                    <div class="card-body">
                                        <h5 class="card-title mb-1"><?php echo $judul; ?></h5>
                                        <p class="card-text text-muted small mb-1"><?php echo $tanggal; ?></p>
                                        <p class="card-text small"><?php echo $ringkasan; ?></p>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php 
                    endforeach; 
                else: 
                ?>
                    <div class="col-12">
                        <p class="text-muted text-center">Belum ada berita.</p>
                    </div>
                <?php endif; ?>
                    </div>
                </div>
                
                <!-- Navigation buttons -->
                <button class="news-slider-btn news-slider-prev" onclick="slideBerita('prev')">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button class="news-slider-btn news-slider-next" onclick="slideBerita('next')">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>
</div>


               <?php include 'includes/sidebar-right.php'; ?>
     </section>

    </section>




     <!-- Video Section -->
     <section class="video-slider-section">
         <div class="video-header-bar">
             <h6 class="video-title-header">Video</h6>
         </div>
         <div class="video-slider-container">
             <!-- Navigation Arrows - Separate from slider -->
             <button class="video-nav-btn video-prev" id="videoPrev">
                 <i class="fas fa-chevron-left"></i>
             </button>
             <button class="video-nav-btn video-next" id="videoNext">
                 <i class="fas fa-chevron-right"></i>
             </button>
             
             <div class="video-slider-wrapper">
                 <!-- Video Slider Track -->
                 <div class="video-slider-track" id="videoSliderTrack">
                     <?php if (!empty($videos)): ?>
                         <?php foreach ($videos as $video): ?>
                             <div class="video-card">
                                 <div class="video-player">
                                     <?php 
                                     // Get YouTube video ID and create embed URL
                                     $videoId = extractYouTubeVideoId($video['url_video']);
                                     if ($videoId) {
                                         $embedUrl = convertToEmbedUrl($video['url_video']);
                                     ?>
                                         <iframe src="<?php echo htmlspecialchars($embedUrl); ?>" 
                                                 frameborder="0" 
                                                 allowfullscreen
                                                 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture">
                                         </iframe>
                                     <?php } else { ?>
                                         <div class="video-placeholder">
                                             <i class="fas fa-video"></i>
                                             <p>Video tidak tersedia</p>
                                         </div>
                                     <?php } ?>
                                 </div>
                             </div>
                         <?php endforeach; ?>
                     <?php else: ?>
                         <div class="video-card">
                             <div class="video-thumbnail">
                                 <div class="video-placeholder">
                                     <i class="fas fa-video"></i>
                                 </div>
                             </div>
                         </div>
                     <?php endif; ?>
                 </div>
             </div>
         </div>
     </section>

     <!-- Galeri Infrastruktur Section -->
     <section class="galeri-section infrastructure-bg" style="background-image: url('<?php echo getAssetUrl('img/bg-gallery.png'); ?>');">
        <div class="container-fluid" style="margin: 0;">
            <div class="row">
                <div class="col-12">
                    <h1 class="slider-title">Galeri <strong>Infrastruktur</strong></h1>
                </div>
            </div>

            <!-- Desktop Layout -->
            <div class="d-none d-md-block">
                <div class="slider-wrapper">

                <!-- Left Arrow - OUTSIDE -->
                <button class="nav-arrow prev-arrow" id="prevBtn">
                    <i class="bi bi-chevron-left"></i>
                </button>

                <!-- Right Arrow - OUTSIDE -->
                <button class="nav-arrow next-arrow" id="nextBtn">
                    <i class="bi bi-chevron-right"></i>
                </button>

                <!-- Slider Container -->
                <div class="slider-container">
                    <div class="slider-track" id="sliderTrack" data-original-count="<?php echo min(count($galeri_infrastruktur ?? []), 4); ?>">
                        <?php if (!empty($galeri_infrastruktur)) { 
                            $slidesInfra = array_values(array_slice($galeri_infrastruktur, 0, 4));
                            $countInfra = count($slidesInfra);
                            if ($countInfra <= 1) {
                                foreach ($slidesInfra as $g) {
                                    $img = !empty($g['gambar']) ? $g['gambar'] : 'assets/img/infografis1.jpg';
                                    $title = htmlspecialchars($g['judul'] ?? '');
                        ?>
                        <a href="galeriinfrastruktur.php" class="slide-item" style="text-decoration: none; color: inherit;">
                            <div class="slide-img-wrap">
                                <img src="<?php echo $img; ?>" alt="<?php echo $title; ?>" class="slide-img">
                            </div>
                            <div class="slide-caption"><?php echo $title; ?></div>
                        </a>
                        <?php           }
                            } else {
                                $groups = [array_slice($slidesInfra, -2), $slidesInfra, array_slice($slidesInfra, 0, 2)];
                                foreach ($groups as $arr) {
                                    foreach ($arr as $g) {
                                        $img = !empty($g['gambar']) ? $g['gambar'] : 'assets/img/infografis1.jpg';
                                        $title = htmlspecialchars($g['judul'] ?? '');
                        ?>
                        <a href="galeriinfrastruktur.php" class="slide-item" style="text-decoration: none; color: inherit;">
                            <div class="slide-img-wrap">
                                <img src="<?php echo $img; ?>" alt="<?php echo $title; ?>" class="slide-img">
                            </div>
                            <div class="slide-caption"><?php echo $title; ?></div>
                        </a>
                        <?php               }
                                }
                            }
                        } else { ?>
                        <a href="galeriinfrastruktur.php" class="slide-item" style="text-decoration: none; color: inherit;">
                            <div class="slide-img-wrap" style="background:#cfcfcf;"></div>
                            <div class="slide-caption">Belum Ada Galeri Infrastruktur</div>
                        </a>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- MOBILE RESPONSIVE SLIDER -->
        <div class="d-block d-md-none">
          <div class="mobile-slider">
            <div class="mobile-slider-track" id="mobileSliderTrack">
              <?php if (!empty($galeri_infrastruktur)) { 
                $slidesInfra = array_values(array_slice($galeri_infrastruktur, 0, 4));
                foreach ($slidesInfra as $g) {
                  $img = !empty($g['gambar']) ? $g['gambar'] : 'assets/img/infografis1.jpg';
                  $title = htmlspecialchars($g['judul'] ?? '');
              ?>
              <a href="galeriinfrastruktur.php" class="mobile-slide" style="text-decoration: none; color: inherit;">
                <img src="<?php echo $img; ?>" alt="<?php echo $title; ?>">
                <div class="mobile-caption"><?php echo $title; ?></div>
              </a>
              <?php } } else { ?>
              <a href="galeriinfrastruktur.php" class="mobile-slide" style="text-decoration: none; color: inherit;">
                <div class="mobile-placeholder">
                  <i class="fas fa-images"></i>
                </div>
                <div class="mobile-caption">Belum Ada Galeri Infrastruktur</div>
              </a>
              <?php } ?>
            </div>

            <!-- Arrows -->
            <button class="mobile-nav prev" id="mobilePrev"><i class="fas fa-chevron-left"></i></button>
            <button class="mobile-nav next" id="mobileNext"><i class="fas fa-chevron-right"></i></button>
          </div>
        </div>
        </div>
    </div>
</section>



<!-- Aplikasi & Link Terkait Section - Mobile Responsive -->
<section class="apps-section py-5" >
<h4 class="fw-bold mb-5 apps-section-title">
                <strong>Aplikasi</strong> & <strong>Link Terkait</strong>
            </h4>

<div class="logos">
    <div class="logos-slide">
        <a href="https://pdsda.sda.pu.go.id/"><img src="assets/logo/wrdc_logo.gif" alt="Logo 1"></a>
        <a href="https://sihka.sda.pu.go.id/"><img src="assets/logo/sihka-logo.gif" alt="Logo 2"></a>
        <a href="https://perizinansda.pu.go.id/"><img src="assets/logo/perizinan.gif" alt="Logo 3"></a>
        <a href="https://www.lapor.go.id/"><img src="assets/logo/lapor.png" alt="Logo 6"></a>
        <a href="https://jdih.pu.go.id/"><img src="assets/logo/jdih-logo.jpg" alt="Logo 7"></a>
        <a href="https://sigi.pu.go.id/astv2/"><img src="assets/logo/sigi-logo.gif" alt="Logo 8"></a>
        <a href="https://www.bmkg.go.id/"><img src="assets/logo/logo-bmkg.png" alt="Logo 9"></a>
        <a href="https://sippn.menpan.go.id/"><img src="assets/logo/sippn.jpg" alt="Logo 10"></a>
        <a href="https://sahabat.pu.go.id/eppid/"><img src="assets/logo/eppid.svg" alt="Logo 11"></a>
        <a href="https://wispu.pu.go.id/"><img src="assets/logo/wispu.png" alt="Logo 12"></a>
    </div>
</div>

    </section>

    <script>
    var copy = document.querySelector(".logos-slide").cloneNode(true);
    document.querySelector(".logos").appendChild(copy);
</script>


<a href="https://wa.me/628118150505" class="whatsapp-float" target="_blank">
  <img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" alt="WhatsApp" />
</a>

<style>
.whatsapp-float {
  position: fixed;
  width: 60px;
  height: 60px;
  bottom: 20px;
  right: 20px;
  background-color: #25d366;
  border-radius: 50%;
  box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease; /* transisi lembut */
}

.whatsapp-float img {
  width: 35px;
  height: 35px;
  transition: transform 0.3s ease;
}

.whatsapp-float:hover {
  background-color: #20ba5a; /* warna lebih gelap */
  transform: scale(1.1);    /* membesar sedikit */
  box-shadow: 4px 4px 12px rgba(0,0,0,0.4);
}

.whatsapp-float:hover img {
  transform: rotate(10deg); /* ikon berputar sedikit */
}
</style>

<script>
// Video Slider
document.addEventListener('DOMContentLoaded', function() {
    const videoSliderTrack = document.getElementById('videoSliderTrack');
    const videoPrevBtn = document.getElementById('videoPrev');
    const videoNextBtn = document.getElementById('videoNext');
    
    if (videoSliderTrack && videoPrevBtn && videoNextBtn) {
        const videoCards = videoSliderTrack.querySelectorAll('.video-card');
        const totalVideos = videoCards.length;
        let currentVideoIndex = totalVideos > 1 ? 1 : 0; // Start from slide 2 if available, otherwise slide 1
        const videosToShow = 1.67; // Show 1.67 videos at once (1 focused in center)
        const videoSlideWidth = 60; // Percentage width per slide (matches CSS)
        
        // Set initial slide width and active state
        videoCards.forEach((card, index) => {
            card.style.width = videoSlideWidth + '%';
            if (index === currentVideoIndex) { // Set current slide as active
                card.classList.add('active');
            } else {
                card.classList.remove('active');
            }
        });
        
        function updateVideoSlider() {
            // Start from the beginning (left) - no centering offset
            const translateX = -currentVideoIndex * videoSlideWidth;
            videoSliderTrack.style.transform = `translateX(${translateX}%)`;
            
            // Update active state - current video is active
            videoCards.forEach((card, index) => {
                if (index === currentVideoIndex) {
                    card.classList.add('active');
                } else {
                    card.classList.remove('active');
                }
            });
            
            // Update button states
            videoPrevBtn.disabled = currentVideoIndex === 0;
            videoNextBtn.disabled = currentVideoIndex >= totalVideos - 1;
        }
        
        videoPrevBtn.addEventListener('click', function() {
            if (currentVideoIndex > 0) {
                currentVideoIndex--;
                updateVideoSlider();
            }
        });
        
        videoNextBtn.addEventListener('click', function() {
            if (currentVideoIndex < totalVideos - 1) {
                currentVideoIndex++;
                updateVideoSlider();
            }
        });
        
        // Initialize
        updateVideoSlider();
    }
});


// Berita Grid Slider
document.addEventListener('DOMContentLoaded', function() {
    const sliderTrack = document.getElementById('beritaGridSliderTrack');
    const prevBtn = document.getElementById('beritaGridPrev');
    const nextBtn = document.getElementById('beritaGridNext');
    
    if (sliderTrack && prevBtn && nextBtn) {
        let currentIndex = 0;
        const slides = sliderTrack.querySelectorAll('.berita-slide');
        const totalSlides = slides.length;
        const slidesToShow = 3; // Show 3 cards at once
        const slideWidth = 100 / slidesToShow; // Percentage width per slide
        
        // Set initial slide width
        slides.forEach(slide => {
            slide.style.width = slideWidth + '%';
        });
        
        function updateSlider() {
            const translateX = -currentIndex * slideWidth;
            sliderTrack.style.transform = `translateX(${translateX}%)`;
            
            // Update button states
            prevBtn.disabled = currentIndex === 0;
            nextBtn.disabled = currentIndex >= totalSlides - slidesToShow;
        }
        
        prevBtn.addEventListener('click', function() {
            if (currentIndex > 0) {
                currentIndex--;
                updateSlider();
            }
        });
        
        nextBtn.addEventListener('click', function() {
            if (currentIndex < totalSlides - slidesToShow) {
                currentIndex++;
                updateSlider();
            }
        });
        
        // Initialize
        updateSlider();
    }
});
</script>

<!-- Notification Popup Script -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Index page loaded, checking for notification popup...');
    
    // Check if notification is active via AJAX
    fetch('api/notification-settings.php')
        .then(response => response.json())
        .then(data => {
            console.log('Notification settings:', data);
            
            if (data.success && data.is_active) {
                console.log('Notification is active, showing popup...');
                
                // Create popup HTML - hanya gambar
                const popupHTML = `
                    <div id="notificationOverlay" class="notification-overlay" style="display: none;">
                        <div class="notification-popup">
                            <button class="notification-close" onclick="hideNotificationPopup()">&times;</button>
                            <div class="notification-content">
                                <img src="${data.image_path}" alt="Notification Image" class="notification-image">
                            </div>
                        </div>
                    </div>
                `;
                
                // Add popup to body
                document.body.insertAdjacentHTML('beforeend', popupHTML);
                
                // Show popup after 2 seconds
                setTimeout(() => {
                    const overlay = document.getElementById('notificationOverlay');
                    if (overlay) {
                        // Disable scroll on body
                        document.body.style.overflow = 'hidden';
                        document.body.style.position = 'fixed';
                        document.body.style.width = '100%';
                        
                        overlay.style.display = 'flex';
                        setTimeout(() => {
                            overlay.classList.add('show');
                        }, 100);
                    }
                }, 2000);
                
                // Close on overlay click
                document.getElementById('notificationOverlay').addEventListener('click', function(e) {
                    if (e.target === this) {
                        hideNotificationPopup();
                    }
                });
                
            } else {
                console.log('Notification is not active or no data found');
            }
        })
        .catch(error => {
            console.error('Error loading notification settings:', error);
        });
});

function hideNotificationPopup() {
    const overlay = document.getElementById('notificationOverlay');
    if (overlay) {
        overlay.classList.remove('show');
        setTimeout(() => {
            overlay.style.display = 'none';
            
            // Re-enable scroll on body
            document.body.style.overflow = '';
            document.body.style.position = '';
            document.body.style.width = '';
        }, 300);
    }
}
</script>

<style>
.notification-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.notification-overlay.show {
    opacity: 1;
    visibility: visible;
}

.notification-popup {
    background: white;
    border-radius: 15px;
    padding: 20px;
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    position: relative;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    transform: scale(0.8);
    transition: transform 0.3s ease;
}

.notification-overlay.show .notification-popup {
    transform: scale(1);
}

.notification-close {
    position: absolute;
    top: 15px;
    right: 20px;
    background: #666;
    color: white;
    border: none;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    font-size: 18px;
    cursor: pointer;
    z-index: 10;
}

.notification-content {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}

.notification-image {
    max-width: 100%;
    max-height: 60vh;
    height: auto;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}


@media (max-width: 768px) {
    .notification-popup {
        width: 95%;
        margin: 10px;
    }
    
    .notification-image {
        max-width: 100%;
        max-height: 50vh;
    }
}
</style>

<?php
// Include footer
include 'includes/footer.php';
?>
