<?php
// Enable error reporting at the TOP of the file
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Start output buffering to catch any stray output
ob_start();

include_once 'inc/dbconn.php';

// Check if database connection is successful
if (!isset($pdo) || !($pdo instanceof PDO)) {
    die("Database connection failed");
}

try {
    // Get total count for pagination
    $countSql = "SELECT COUNT(*) as total FROM portfolio WHERE publish_status = 1";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute();
    $result = $countStmt->fetch(PDO::FETCH_ASSOC);
    $totalCount = $result ? $result['total'] : 0;
    
    // Fetch portfolio items - limit to reasonable number
    $sql = "SELECT id, title, slug, images, description, video_link, created_at 
            FROM portfolio 
            WHERE publish_status = 1 
            ORDER BY RAND() 
            LIMIT 9";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $portfolioItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    // Log the error but don't show sensitive info to users
    error_log("Database error: " . $e->getMessage());
    $portfolioItems = [];
    $totalCount = 0;
    echo "<!-- Database error occurred -->";
}

// Clear any stray output
ob_end_clean();
?>

     <?php if (!empty($portfolioItems)): ?>
        <!-- Portfolio Gallery Section -->
        <div class="portfolio-gallery-section p-relative pt-20 pb-50" style="background-color: #ffffff;">
            <div class="container">
                <!-- Section Header -->
                <div class="portfolio-title-wrap p-relative mb-60">
                    <div class="row align-items-end">
                        <div class="col-xl-8 col-lg-8 col-md-8">
                            <div class="portfolio-title-box">
                                <span class="portfolio-subtitle" style="color: #7A1E2B; font-size: 16px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; display: block; margin-bottom: 15px;">
                                    Student Showcase
                                </span>
                                <h4 class="portfolio-title" style="color: #000000; font-size: 42px; font-weight: 700; line-height: 1.2; margin: 0;">
                                    Celebrating Excellence in<br>
                                    Drama, Arts & Graduations
                                </h4>
                            </div>
                        </div>
                        <div class="col-xl-4 col-lg-4 col-md-4 text-end">
                            <a href="portfolio.php" class="view-all-btn" style="display: inline-flex; align-items: center; color: #7A1E2B; text-decoration: none; font-weight: 600; font-size: 16px; padding: 10px 25px; border: 2px solid #7A1E2B; border-radius: 25px; transition: all 0.3s ease;">
                                View All Projects
                                <svg width="18" height="14" viewBox="0 0 17 14" fill="none" style="margin-left: 8px; transition: transform 0.3s ease;">
                                    <path d="M11 1.24023L16 7.24023L11 13.2402" stroke="#7A1E2B" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round" />
                                    <path d="M1 7.24023H16" stroke="#7A1E2B" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round" />
                                </svg>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Portfolio Carousel -->
                <div class="portfolio-carousel-container" style="position: relative; padding: 0 60px;">
                    <!-- Navigation Arrows -->
                    <button class="carousel-prev" type="button" style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); z-index: 10; width: 50px; height: 50px; background: white; color: #7A1E2B; border: 2px solid #7A1E2B; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    
                    <button class="carousel-next" type="button" style="position: absolute; right: 0; top: 50%; transform: translateY(-50%); z-index: 10; width: 50px; height: 50px; background: white; color: #7A1E2B; border: 2px solid #7A1E2B; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                    
                    <!-- Carousel Track -->
                    <div class="portfolio-carousel-track" style="display: flex; gap: 30px; overflow: hidden; padding: 10px;">
                        <?php foreach($portfolioItems as $item): ?>
                            <?php
                            // Safely extract data
                            $itemId = htmlspecialchars($item['id'] ?? '');
                            $images = !empty($item['images']) ? explode(',', $item['images']) : [];
                            
                            // Get first image
                            $firstImage = '';
                            if (!empty($images[0])) {
                                $firstImage = trim($images[0]);
                                // Clean up path
                                $firstImage = str_replace(['assets/img/', 'portfolio_images/'], '', $firstImage);
                            }
                            
                            $imagePath = !empty($firstImage) ? "portfolio_images/{$firstImage}" : "assets/img/placeholder.jpg";
                            $slug = htmlspecialchars($item['slug'] ?? '');
                            $title = htmlspecialchars($item['title'] ?? 'Untitled');
                            
                            // Clean description
                            $description = '';
                            if (!empty($item['description'])) {
                                $cleanDesc = strip_tags($item['description']);
                                $description = strlen($cleanDesc) > 100 ? substr($cleanDesc, 0, 100) . '...' : $cleanDesc;
                            } else {
                                $description = 'No description available.';
                            }
                            
                            $videoLink = htmlspecialchars($item['video_link'] ?? '');
                            ?>
                            
                            <!-- Portfolio Item -->
                            <div class="carousel-item" style="flex: 0 0 calc(33.333% - 20px); min-width: 300px; transition: transform 0.3s ease;">
                                <div class="portfolio-card" style="border: 1px solid #f0f0f0; border-radius: 12px; overflow: hidden; transition: all 0.3s ease; height: 100%; box-shadow: 0 5px 15px rgba(0,0,0,0.05);">
                                    <!-- Media Container -->
                                    <div class="portfolio-media" style="position: relative; overflow: hidden; height: 280px;">
                                        <?php if(!empty($videoLink)): ?>
                                            <!-- Video Thumbnail -->
                                            <div class="video-thumbnail" style="position: relative; height: 100%; cursor: pointer;" data-video="<?php echo $videoLink; ?>">
                                                <img src="assets/img/placeholder.jpg" 
                                                    data-src="<?php echo $imagePath; ?>" 
                                                    alt="<?php echo $title; ?>" 
                                                    class="lazy"
                                                    style="width: 100%; height: 100%; object-fit: cover; background: #f5f5f5; transition: transform 0.5s ease;"
                                                    onerror="this.src='assets/img/placeholder.jpg'">
                                                <div class="video-overlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(122, 30, 43, 0.7); display: flex; align-items: center; justify-content: center; opacity: 0.9; transition: opacity 0.3s ease;">
                                                    <div class="play-button" style="width: 60px; height: 60px; background: white; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="#7A1E2B">
                                                            <path d="M8 5v14l11-7z"/>
                                                        </svg>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <!-- Image Gallery -->
                                            <div class="image-gallery" style="position: relative; height: 100%;">
                                                <img src="assets/img/placeholder.jpg" 
                                                    data-src="<?php echo $imagePath; ?>" 
                                                    alt="<?php echo $title; ?>" 
                                                    class="lazy"
                                                    style="width: 100%; height: 100%; object-fit: cover; background: #f5f5f5; transition: transform 0.5s ease;"
                                                    onerror="this.src='assets/img/placeholder.jpg'">
                                                <?php if(count($images) > 1): ?>
                                                    <div class="gallery-indicator" style="position: absolute; top: 15px; right: 15px; background: white; color: #7A1E2B; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 14px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                                                        +<?php echo count($images) - 1; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Content -->
                                    <div class="portfolio-content" style="padding: 25px; background: white;">
                                        <h5 class="portfolio-item-title" style="color: #000000; font-size: 20px; font-weight: 600; margin: 0 0 15px 0; line-height: 1.3;">
                                            <?php echo $title; ?>
                                        </h5>
                                        <p class="portfolio-description" style="color: #666666; font-size: 15px; line-height: 1.6; margin: 0 0 20px 0; min-height: 48px;">
                                            <?php echo $description; ?>
                                        </p>
                                        
                                        <!-- View Button -->
                                        <a href="blog-details.php?slug=<?php echo $slug; ?>" class="view-more-btn" style="display: inline-flex; align-items: center; color: #7A1E2B; text-decoration: none; font-weight: 600; font-size: 14px; padding: 8px 20px; border: 2px solid #7A1E2B; border-radius: 25px; transition: all 0.3s ease;">
                                            View Details
                                            <svg width="16" height="12" viewBox="0 0 17 14" fill="none" style="margin-left: 8px; transition: transform 0.3s ease;">
                                                <path d="M11 1.24023L16 7.24023L11 13.2402" stroke="#7A1E2B" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round" />
                                                <path d="M1 7.24023H16" stroke="#7A1E2B" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round" />
                                            </svg>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Carousel Dots - FIXED CALCULATION -->
                <div class="carousel-dots" style="display: flex; justify-content: center; gap: 8px; margin-top: 40px;">
                    <?php 
                    if (!empty($portfolioItems)) {
                        $itemCount = count($portfolioItems);
                        $visibleItems = 3; // Desktop: 3 items visible
                        $dotCount = ceil($itemCount / $visibleItems);
                        
                        // Cap dots at reasonable number
                        $dotCount = min($dotCount, 10);
                        
                        for($i = 0; $i < $dotCount; $i++) {
                            $isActive = $i === 0 ? 'active' : '';
                            echo '<button class="carousel-dot ' . $isActive . '" data-slide="' . $i . '" style="width: 12px; height: 12px; border-radius: 50%; border: 2px solid #7A1E2B; background: ' . ($i === 0 ? '#7A1E2B' : 'transparent') . '; cursor: pointer; transition: all 0.3s ease;"></button>';
                        }
                    }
                    ?>
                </div>
            </div>
        </div>

        <!-- SIMPLIFIED JAVASCRIPT - Much safer -->
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Basic carousel functionality
            const track = document.querySelector('.portfolio-carousel-track');
            const items = document.querySelectorAll('.carousel-item');
            const prevBtn = document.querySelector('.carousel-prev');
            const nextBtn = document.querySelector('.carousel-next');
            const dots = document.querySelectorAll('.carousel-dot');
            
            if (!track || items.length === 0) return;
            
            let currentPosition = 0;
            let autoSlideInterval;
            
            // Function to move carousel
            function moveCarousel(direction) {
                const itemWidth = items[0].offsetWidth;
                const gap = 30;
                const visibleItems = getVisibleItems();
                const slideWidth = (itemWidth + gap) * visibleItems;
                const maxPosition = Math.max(0, (items.length - visibleItems) * slideWidth);
                
                if (direction === 'next') {
                    currentPosition = Math.min(currentPosition + slideWidth, maxPosition);
                    if (currentPosition >= maxPosition) {
                        currentPosition = 0; // Loop back
                    }
                } else {
                    currentPosition = Math.max(currentPosition - slideWidth, 0);
                    if (currentPosition <= 0) {
                        currentPosition = maxPosition; // Loop to end
                    }
                }
                
                track.style.transition = 'transform 0.5s ease';
                track.style.transform = `translateX(-${currentPosition}px)`;
                
                updateDots();
            }
            
            // Get visible items based on screen size
            function getVisibleItems() {
                if (window.innerWidth < 768) return 1;
                if (window.innerWidth < 992) return 2;
                return 3;
            }
            
            // Update dot indicators
            function updateDots() {
                const visibleItems = getVisibleItems();
                const itemWidth = items[0].offsetWidth;
                const gap = 30;
                const slideWidth = (itemWidth + gap) * visibleItems;
                const currentSlide = Math.floor(currentPosition / slideWidth);
                
                dots.forEach((dot, index) => {
                    dot.classList.toggle('active', index === currentSlide);
                    dot.style.background = index === currentSlide ? '#7A1E2B' : 'transparent';
                });
            }
            
            // Start auto slide
            function startAutoSlide() {
                stopAutoSlide();
                autoSlideInterval = setInterval(() => {
                    moveCarousel('next');
                }, 4000);
            }
            
            // Stop auto slide
            function stopAutoSlide() {
                if (autoSlideInterval) {
                    clearInterval(autoSlideInterval);
                }
            }
            
            // Event listeners
            if (prevBtn) {
                prevBtn.addEventListener('click', () => {
                    moveCarousel('prev');
                    resetAutoSlide();
                });
            }
            
            if (nextBtn) {
                nextBtn.addEventListener('click', () => {
                    moveCarousel('next');
                    resetAutoSlide();
                });
            }
            
            // Dot navigation
            dots.forEach(dot => {
                dot.addEventListener('click', function() {
                    const slideIndex = parseInt(this.getAttribute('data-slide'));
                    const visibleItems = getVisibleItems();
                    const itemWidth = items[0].offsetWidth;
                    const gap = 30;
                    const slideWidth = (itemWidth + gap) * visibleItems;
                    
                    currentPosition = slideIndex * slideWidth;
                    track.style.transition = 'transform 0.5s ease';
                    track.style.transform = `translateX(-${currentPosition}px)`;
                    
                    updateDots();
                    resetAutoSlide();
                });
            });
            
            // Pause on hover
            track.addEventListener('mouseenter', stopAutoSlide);
            track.addEventListener('mouseleave', startAutoSlide);
            
            // Handle resize
            window.addEventListener('resize', () => {
                updateDots();
            });
            
            // Video click
            document.querySelectorAll('.video-thumbnail').forEach(thumb => {
                thumb.addEventListener('click', function() {
                    const videoUrl = this.getAttribute('data-video');
                    if (videoUrl) {
                        window.open(videoUrl, '_blank');
                    }
                });
            });
            
            // Lazy load images
            const lazyImages = document.querySelectorAll('img.lazy');
            lazyImages.forEach(img => {
                if (img.getAttribute('data-src')) {
                    img.src = img.getAttribute('data-src');
                    img.onload = () => img.classList.remove('lazy');
                }
            });
            
            // Initialize
            updateDots();
            startAutoSlide();
        });
        </script>

        <?php else: ?>
        <!-- No items message -->
        <div class="container py-5">
            <div class="text-center">
                <p style="color: #666; font-size: 18px;">No portfolio items found.</p>
            </div>
        </div>
        <?php endif; ?>

    <style>
         /* Carousel Styling */
         .portfolio-carousel-track {
            cursor: grab;
         }
         
         .portfolio-carousel-track:active {
            cursor: grabbing;
         }
         
         /* Card Hover Effects */
         .portfolio-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 35px rgba(122, 30, 43, 0.15);
         }
         
         .portfolio-media img {
            transition: transform 0.5s ease;
         }
         
         .portfolio-card:hover .portfolio-media img {
            transform: scale(1.08);
         }
         
         .video-thumbnail:hover .video-overlay,
         .image-gallery:hover .video-overlay {
            opacity: 1;
         }
         
         /* Button Hover Effects */
         .view-more-btn:hover {
            background: #7A1E2B;
            color: white;
         }
         
         .view-more-btn:hover svg path {
            stroke: white;
         }
         
         .view-more-btn:hover svg {
            transform: translateX(5px);
         }
         
         .view-all-btn:hover {
            background: #7A1E2B;
            color: white;
         }
         
         .view-all-btn:hover svg path {
            stroke: white;
         }
         
         .view-all-btn:hover svg {
            transform: translateX(5px);
         }
         
         /* Arrow Hover Effects */
         .carousel-prev:hover,
         .carousel-next:hover {
            background: #7A1E2B;
            color: white;
            transform: translateY(-50%) scale(1.1);
         }
         
         /* Active Dot */
         .carousel-dot.active {
            background: #7A1E2B !important;
            transform: scale(1.2);
         }
         
         /* Responsive */
         @media (max-width: 991px) {
            .carousel-item {
                  flex: 0 0 calc(50% - 15px) !important;
            }
            
            .portfolio-carousel-container {
                  padding: 0 40px !important;
            }
            
            .carousel-prev,
            .carousel-next {
                  width: 40px !important;
                  height: 40px !important;
            }
         }
         
         @media (max-width: 767px) {
            .carousel-item {
                  flex: 0 0 100% !important;
            }
            
            .portfolio-carousel-container {
                  padding: 0 30px !important;
            }
            
            .portfolio-title {
                  font-size: 32px !important;
            }
         }
      </style>
