<?php
// File: news.php

// 1. ERROR REPORTING
ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'header.php';

// --- HELPER 1: Extract YouTube ID ---
function getYoutubeId($url) {
    if (empty($url)) return null;
    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
    return isset($match[1]) ? $match[1] : null;
}

// --- HELPER 2: Render a Single Article Card ---
// We use a function to avoid repeating the same HTML code twice
function renderArticleCard($row) {
    // Setup Video/Image Logic
    $is_video = false;
    $video_id = null;
    
    if (isset($row['video_url']) && !empty($row['video_url'])) {
        $video_id = getYoutubeId($row['video_url']);
        if ($video_id) $is_video = true;
    }

    if ($is_video) {
        $display_image = "https://img.youtube.com/vi/$video_id/hqdefault.jpg";
        $badge_text = "Video";
        $badge_color = "bg-red-100 text-red-800";
    } else {
        $display_image = !empty($row['image_path']) ? $row['image_path'] : 'assets/images/default-news.jpg';
        $badge_text = !empty($row['category']) ? htmlspecialchars($row['category']) : 'News';
        $badge_color = "bg-ucf-green-light text-ucf-green-dark";
    }

    $date = isset($row['created_at']) ? date("M j, Y", strtotime($row['created_at'])) : '';
    $title = htmlspecialchars($row['title']);
    $excerpt = htmlspecialchars(substr(strip_tags($row['content'] ?? ''), 0, 100)) . '...';

    // Output the Card HTML
    ob_start(); 
    ?>
    <div class="bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow duration-300 flex flex-col overflow-hidden h-full border border-gray-100">
        
        <div class="w-full h-48 bg-gray-200 relative group">
            <?php if ($is_video): ?>
                <div class="w-full h-full cursor-pointer relative video-placeholder" 
                     onclick="loadYoutubePlayer(this, '<?php echo $video_id; ?>')">
                    <img src="<?php echo $display_image; ?>" class="w-full h-full object-cover">
                    <div class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-30 group-hover:bg-opacity-10 transition-all">
                        <div class="bg-red-600 text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg transform group-hover:scale-110 transition-transform">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 ml-1" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd" /></svg>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <a href="article_single.php?id=<?php echo $row['id']; ?>" class="block h-full w-full">
                    <img src="<?php echo htmlspecialchars($display_image); ?>" class="w-full h-full object-cover hover:scale-105 transition-transform duration-300">
                </a>
            <?php endif; ?>
        </div>

        <div class="p-5 flex-1 flex flex-col">
            <div class="mb-2">
                <span class="inline-block <?php echo $badge_color; ?> text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wide">
                    <?php echo $badge_text; ?>
                </span>
            </div>
            <h3 class="text-lg font-bold text-ucf-charcoal hover:text-ucf-green transition-colors line-clamp-2 mb-2 leading-tight">
                <a href="article_single.php?id=<?php echo $row['id']; ?>"><?php echo $title; ?></a>
            </h3>
            <p class="text-gray-500 text-xs line-clamp-3 mb-4 flex-grow"><?php echo $excerpt; ?></p>
            <div class="pt-3 border-t border-gray-100 text-xs text-gray-400 flex items-center">
                <i class="far fa-calendar-alt mr-2"></i> <?php echo $date; ?>
            </div>
        </div>
    </div>
    <?php 
    return ob_get_clean();
}


// 2. FETCH & ORGANIZE DATA
$articles = [];
$sql = "SELECT * FROM articles ORDER BY created_at DESC";

if (isset($conn)) {
    $result = $conn->query($sql);
    if ($result) {
        $articles = $result->fetch_all(MYSQLI_ASSOC);
    }
}

// Split Data: Top 4 vs The Rest
$latest_updates = array_slice($articles, 0, 4); // First 4
$remaining_articles = array_slice($articles, 4); // All after the first 4

// Group "The Rest" by Category
$categorized_news = [];
foreach ($remaining_articles as $item) {
    $cat = !empty($item['category']) ? $item['category'] : 'General';
    $categorized_news[$cat][] = $item;
}
?>

<div class="bg-gray-50 py-10 min-h-screen">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        <div class="text-center mb-10">
            <h1 class="text-3xl font-extrabold text-ucf-charcoal sm:text-4xl tracking-tight">Art News & Updates</h1>
            <p class="mt-2 text-gray-500">The latest stories from our vibrant art community.</p>
        </div>

        <?php if (!empty($latest_updates)): ?>
            <div class="mb-16">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-2xl font-bold text-ucf-charcoal border-l-4 border-ucf-green pl-3">
                        Latest Uploads
                    </h2>
                </div>
                
                <div class="grid gap-6 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
                    <?php foreach ($latest_updates as $row): ?>
                        <?php echo renderArticleCard($row); ?>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>


        <?php if (!empty($categorized_news)): ?>
            <?php foreach ($categorized_news as $category_name => $items): ?>
                <div class="mb-12">
                    <div class="flex items-center mb-6">
                        <h2 class="text-2xl font-bold text-gray-800 mr-4">
                            <?php echo htmlspecialchars($category_name); ?>
                        </h2>
                        <div class="h-px bg-gray-200 flex-grow"></div>
                    </div>

                    <div class="grid gap-6 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
                        <?php foreach ($items as $row): ?>
                            <?php echo renderArticleCard($row); ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        
        <?php elseif (empty($latest_updates)): ?>
            <div class="text-center py-16 bg-white rounded-lg shadow-sm">
                <div class="text-6xl text-gray-300 mb-4">📰</div>
                <h2 class="text-2xl font-bold text-ucf-charcoal">No News Found</h2>
                <p class="text-gray-500 mt-2">Please check back later for updates.</p>
            </div>
        <?php endif; ?>

    </div>
</div>

<script>
function loadYoutubePlayer(container, videoId) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('src', 'https://www.youtube.com/embed/' + videoId + '?autoplay=1&rel=0');
    iframe.setAttribute('width', '100%');
    iframe.setAttribute('height', '100%');
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture');
    iframe.setAttribute('allowfullscreen', 'true');
    container.innerHTML = '';
    container.appendChild(iframe);
}
</script>

<?php include 'footer.php'; ?>