<?php
/**
 * Agentic Square - Dynamic Recent Products Components Layer
 * Path: sections/recentproducts.php
 */

try {
    /**
     * DATABASE HYDRATION LAYER
     * Fetches the 4 most recent active assets mapped with their category properties.
     */
    $recentItemsQuery = $pdo->query("
    SELECT
        i.*,
        c.category_name,

        (
            SELECT COUNT(*)
            FROM orders o
            WHERE o.item_id = i.id
            AND o.payment_status = 'Paid'
        ) AS total_sales,

        (
            SELECT COUNT(*)
            FROM reviews r
            WHERE r.item_id = i.id
        ) AS total_reviews,

        (
            SELECT ROUND(AVG(r.rating),1)
            FROM reviews r
            WHERE r.item_id = i.id
        ) AS average_rating

    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    WHERE i.status = 'active'
    ORDER BY i.id DESC
    LIMIT 4
");

$recentItems = $recentItemsQuery->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Graceful production fallback error container logging
    $recentItems = [];
    error_log("Recent Products Query Exception Context: " . $e->getMessage());
}
?>

<!-- RECENT ARTIFACTS SECTION ENGINE -->
<section id="recent-items" class="recent-items py-20 bg-gradient-to-b from-transparent via-nftCard/10 to-transparent relative">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <!-- HEADER HEADLINE CONTROLS CONTAINER -->
        <div class="flex flex-col md:flex-row md:items-end justify-between mb-12">
            <div>
                <span class="text-xs font-bold tracking-widest text-nftAccentPurple uppercase block mb-2">// Fresh Additions</span>
                <h2 class="text-3xl md:text-4xl font-bold tracking-tight">Recent Machine Code & UI Assets</h2>
            </div>
            <div class="mt-4 md:mt-0 flex space-x-3 overflow-x-auto pb-2">
                <button class="filter-btn active px-5 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all">All Products</button>
                <button class="filter-btn px-5 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all">AI SaaS Scripts</button>
                <button class="filter-btn px-5 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all">AI Web Apps</button>
                <button class="filter-btn px-5 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all">Automation Engines</button>
            </div>
        </div>

        <!-- CORE ITEMS GRID INTERFACE STACK -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            
            <?php if (!empty($recentItems)): ?>
                <?php foreach ($recentItems as $product): ?>
                    <!-- START CARD REPETITION WRAPPER BLOCK -->
                    <div class="nft-card-ui p-4 bg-nftCard/30 rounded-2xl border border-slate-800/80 group flex flex-col justify-between">
                        <div>
                            <!-- Core Asset Media Stage Containment Port -->
                            <div class="relative overflow-hidden rounded-xl aspect-[4/3] mb-4 bg-slate-900">
                                <img src="<?php echo htmlspecialchars(media_url($product['feature_image'] ?? '', 'assets/img/placeholder.png'), ENT_QUOTES, 'UTF-8'); ?>" 
                                     alt="<?php echo htmlspecialchars($product['item_name']); ?> Visualization Image" 
                                     class="w-full h-full object-cover group-hover:scale-105 transition-all duration-500">
                                
                                <!-- Dynamic Category Tag Overlay Flag Component -->
                                <div class="absolute top-3 left-3 bg-nftDark/80 backdrop-blur-md px-2.5 py-1 rounded-md text-[10px] font-bold text-nftAccentCyan uppercase">
                                    <?php echo htmlspecialchars($product['category_name'] ?? 'Asset Core'); ?>
                                </div>
                            </div>

                            <!-- Meta Analytics Line Matrix Info Field Row -->
                            <div class="flex items-center justify-between mb-1">
                                <span class="text-[11px] text-nftTextGray">
                                    Owner Profile: #<?php echo htmlspecialchars($product['seller_id']); ?>
                                </span>
                                <?php if (!empty($product['ai_brain_used'])): ?>
                                    <span class="text-[11px] text-nftAccentPurple font-bold">
                                        <i class="fa-solid fa-brain mr-1 text-[9px]"></i><?php echo htmlspecialchars($product['ai_brain_used']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>

                            <!-- Product Dynamic Route Navigation Header Link -->
                            <!-- Product Dynamic Route Navigation Header Link -->
<h3 class="font-bold text-base hover:text-nftAccentCyan transition-colors cursor-pointer truncate">
    <a href="<?php echo htmlspecialchars(item_url($product)); ?>" class="block" title="<?php echo htmlspecialchars($product['item_name']); ?>">
        <?php echo htmlspecialchars($product['item_name']); ?>
    </a>
</h3>

<div class="flex items-center justify-between mt-3 text-xs">

    <div class="flex items-center text-yellow-400">
        <i class="fas fa-star mr-1"></i>
        <span>
            <?php echo $product['average_rating'] ? number_format($product['average_rating'],1) : '0.0'; ?>
        </span>
    </div>

    <div class="text-cyan-400">
        <i class="fas fa-comment-alt mr-1"></i>
        <?php echo (int)$product['total_reviews']; ?> Reviews
    </div>

    <div class="text-emerald-400">
        <i class="fas fa-shopping-cart mr-1"></i>
        <?php echo (int)$product['total_sales']; ?> Sales
    </div>

</div>
                        </div>

                        <!-- Commercial Monetization Price Action Footer Console Block -->
                        <div class="flex items-center justify-between mt-4 pt-3 border-t border-slate-800/50">
                            <div>
                                <p class="text-[10px] text-nftTextGray uppercase">License Price</p>
                                <p class="text-base font-extrabold text-white font-mono"><?php echo htmlspecialchars(format_currency($product['amount']), ENT_QUOTES, 'UTF-8'); ?></p>
                            </div>
                            
                            <!-- Anchor Redirect Parameter Mapping directly linking into target item-details.php panel layer -->
                            <a href="<?php echo htmlspecialchars(item_url($product)); ?>" 
                               class="bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-white px-4 py-2 rounded-xl text-xs font-semibold shadow-md opacity-90 hover:opacity-100 transition-all text-center inline-block">
                                <i class="fa-solid fa-cart-shopping mr-1 text-[10px]"></i> Purchase Asset
                            </a>
                        </div>
                    </div>
                    <!-- END CARD REPETITION WRAPPER BLOCK -->
                <?php endforeach; ?>
            <?php else: ?>
                <!-- Empty Fallback Index Logic UI Block if Database Row Registry is Clean Empty -->
                <div class="col-span-1 sm:col-span-2 lg:col-span-4 p-8 rounded-2xl border border-dashed border-slate-800 text-center text-nftTextGray text-sm">
                    <i class="fa-solid fa-cubes text-2xl mb-2 block text-slate-700"></i> No digital code components or application configurations registered inside current trace indexes.
                </div>
            <?php endif; ?>

        </div>
    </div>
</section>
