<?php
/**
 * Agentic Square - All Marketplace Products Directory with Live Filters
 * Path: items.php (Main Root Directory)
 */

require_once __DIR__ . '/config/config.php';

// ==========================================
// 1. REAL-TIME ASYNC AJAX CONTROLLER LAYER
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'filter') {
    // Clear out any previous buffer outputs to ensure clean data delivery
    if (ob_get_length()) ob_clean();
    
    try {
        // Decode incoming stream parameters
        $input = json_decode(file_get_contents('php://input'), true);
        
        // Construct secure query matching your exact items and categories schema
        $sql = "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'";
        
        $params = [];
        
        // Dynamic Filter Vector: Title Keyword Search
        if (!empty($input['search'])) {
            $sql .= " AND i.item_name LIKE ?";
            $params[] = "%" . $input['search'] . "%";
        }
        
        // Dynamic Filter Vector: Category ID Link
        if (!empty($input['category'])) {
            $sql .= " AND i.category_id = ?";
            $params[] = (int)$input['category'];
        }
        
        // Dynamic Filter Vector: Price Range Ceiling Cap
        if (isset($input['price'])) {
            $sql .= " AND i.amount <= ?";
            $params[] = (float)$input['price'];
        }
        
        // Sort chronologically by newest additions first
        $sql .= " ORDER BY i.id DESC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($items)) {
            foreach ($items as $product) {
                ?>
                <div class="nft-card-ui p-4 bg-nftCard/30 rounded-2xl border border-slate-800/80 group flex flex-col justify-between">
                    <div>
                        <div class="relative overflow-hidden rounded-xl aspect-[4/3] mb-4 bg-slate-900">
                            <img src="<?= htmlspecialchars(media_url($product['feature_image'] ?? '', 'assets/img/placeholder.png'), ENT_QUOTES, 'UTF-8'); ?>" 
                                 alt="<?= htmlspecialchars($product['item_name']); ?> Thumbnail" 
                                 class="w-full h-full object-cover group-hover:scale-105 transition-all duration-500">
                            
                            <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">
                                <?= htmlspecialchars($product['category_name'] ?? 'Asset Core'); ?>
                            </div>
                        </div>

                        <div class="flex items-center justify-between mb-1">
                            <span class="text-[11px] text-nftTextGray">
                                Owner Profile: #<?= 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><?= htmlspecialchars($product['ai_brain_used']); ?>
                                </span>
                            <?php endif; ?>
                        </div>

                        <h3 class="font-bold text-base hover:text-nftAccentCyan transition-colors cursor-pointer truncate">
                            <a href="<?= htmlspecialchars(item_url($product)); ?>" class="block" title="<?= htmlspecialchars($product['item_name']); ?>">
                                <?= 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>
                                    <?= !empty($product['average_rating']) ? number_format((float)$product['average_rating'], 1) : '0.0'; ?>
                                </span>
                            </div>

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

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

                    <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"><?= htmlspecialchars(format_currency($product['amount']), ENT_QUOTES, 'UTF-8'); ?></p>
                        </div>
                        
                        <a href="<?= 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>
                <?php
            }
        } else {
            ?>
            <div class="col-span-1 sm:col-span-2 lg:col-span-3 p-12 rounded-2xl border border-dashed border-slate-800 text-center text-nftTextGray text-sm w-full">
                <i class="fa-solid fa-cubes text-3xl mb-3 block text-slate-700"></i> 
                No architectural components found matching selected filter options.
            </div>
            <?php
        }
    } catch (Throwable $e) {
        // Send actual system error trace back up to frontend UI context
        http_response_code(500);
        echo "Server Runtime Exception: " . $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine();
    }
    exit;
}

// ==========================================
// 2. STANDARD VISUAL INTERFACE LAYERING
// ==========================================
// Pull categories to build live filtering side console choices
$categories = $pdo->query("SELECT * FROM categories ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);

$page_title = 'All Items';

require_once __DIR__ . '/sections/header.php';
require_once __DIR__ . '/sections/navbar.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <section class="py-12 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 min-h-screen pt-28">
        
        <div class="mb-10 border-b border-slate-900 pb-6">
            <span class="text-xs font-bold tracking-widest text-nftAccentPurple uppercase block mb-1">// Production Code Registry</span>
            <h1 class="text-3xl md:text-4xl font-extrabold tracking-tight">All Machine Code & UI Assets</h1>
        </div>

        <div class="flex flex-col lg:flex-row gap-8">
            
            <aside class="w-full lg:w-72 shrink-0">
                <div class="glass-card bg-slate-950/40 p-6 rounded-2xl border border-slate-800/80 sticky top-28 space-y-6">
                    <div>
                        <h3 class="text-sm font-bold tracking-wider text-white uppercase mb-4 flex items-center gap-2">
                            <i class="fa-solid fa-sliders text-nftAccentCyan text-xs"></i> Control Panel
                        </h3>
                        <hr class="border-slate-900/60 mb-6">
                    </div>

                    <div class="space-y-2">
                        <label class="text-[10px] font-bold uppercase tracking-wider text-nftTextGray">Keyword Search</label>
                        <div class="relative">
                            <input type="text" id="liveSearchInput" placeholder="Filter by asset name..." 
                                   class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl pl-4 pr-10 py-3 text-xs text-white focus:outline-none transition-all">
                            <div class="absolute right-3.5 top-3.5 text-slate-600 pointer-events-none">
                                <i class="fa-solid fa-magnifying-glass text-xs"></i>
                            </div>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label class="text-[10px] font-bold uppercase tracking-wider text-nftTextGray">Classification</label>
                        <select id="categoryFilterInput" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-xs text-white focus:outline-none transition-all">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?= (int)$cat['id'] ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="space-y-2">
                        <div class="flex justify-between items-center text-[10px] font-bold uppercase tracking-wider">
                            <span class="text-nftTextGray">Max Budget Limit</span>
                            <span class="text-nftAccentCyan font-mono" id="priceValueLabel">$1,000</span>
                        </div>
                        <input type="range" id="priceRangeInput" min="0" max="1000" value="1000" step="10" 
                               class="w-full accent-nftAccentCyan bg-slate-900 rounded-lg h-1.5 appearance-none cursor-pointer">
                        <div class="flex justify-between text-[9px] text-slate-600 font-mono">
                            <span>$0</span>
                            <span>$1,000</span>
                        </div>
                    </div>
                </div>
            </aside>

            <main class="flex-1">
                <div id="asyncDirectoryGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    </div>
            </main>
        </div>
    </section>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const liveSearchInput = document.getElementById("liveSearchInput");
            const categoryFilterInput = document.getElementById("categoryFilterInput");
            const priceRangeInput = document.getElementById("priceRangeInput");
            const priceValueLabel = document.getElementById("priceValueLabel");
            const asyncDirectoryGrid = document.getElementById("asyncDirectoryGrid");

            function executeRealtimeFilterPipeline() {
                // Instantly sync visual label text
                priceValueLabel.textContent = `$${Number(priceRangeInput.value).toLocaleString()}`;

                const filterPayload = {
                    search: liveSearchInput.value,
                    category: categoryFilterInput.value,
                    price: priceRangeInput.value
                };

                // Stream request directly back to the self-contained backend process action route
                fetch("<?php echo htmlspecialchars(app_url('items.php?action=filter'), ENT_QUOTES, 'UTF-8'); ?>", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(filterPayload)
                })
                .then(async response => {
                    const outputText = await response.text();
                    if (!response.ok) {
                        // Throws the explicit database exception thrown from PHP try/catch container
                        throw new Error(outputText || "Server responded with an unstable HTTP pipeline error status code.");
                    }
                    return outputText;
                })
                .then(htmlOutputContent => {
                    asyncDirectoryGrid.innerHTML = htmlOutputContent;
                })
                .catch(err => {
                    console.error("Filter Pipeline Sync Exception:", err);
                    asyncDirectoryGrid.innerHTML = `
                        <div class="col-span-1 sm:col-span-2 lg:col-span-3 p-8 bg-rose-500/10 border border-rose-500/20 text-rose-400 rounded-xl text-xs font-mono text-left space-y-2">
                            <p class="font-bold text-sm uppercase text-rose-500">// System Sync Pipeline Terminated</p>
                            <p class="text-slate-300">The async filtering module was unable to fetch records from the storage system core data indexes due to the following diagnostic runtime environment exception error:</p>
                            <div class="p-4 bg-slate-950/60 border border-slate-900 rounded-lg text-rose-300 select-all overflow-x-auto whitespace-pre-wrap">${err.message}</div>
                        </div>`;
                });
            }

            // Bind events for seamless live responsiveness
            liveSearchInput.addEventListener("input", executeRealtimeFilterPipeline);
            categoryFilterInput.addEventListener("change", executeRealtimeFilterPipeline);
            priceRangeInput.addEventListener("input", executeRealtimeFilterPipeline);

            // Trigger fallback mount on initial page rendering
            executeRealtimeFilterPipeline();
        });
    </script>
</body>

<?php 
require_once __DIR__ . '/sections/footer.php'; 
?>
