<?php
// /listing.php
require_once 'includes/header.php';

// --- Breadcrumb & Page Title ---
$breadcrumbs = [
    ['name' => 'Home', 'url' => '/'],
    ['name' => 'Listings', 'url' => '/listing.php']
];

$page_title = 'Browse Listings';
$page_description = "Browse thousands of listings on FexZoh - Nigeria's trusted marketplace. Find deals on cars, electronics, properties, jobs, and more. Filter by category, location, and price.";

if (isset($_GET['category']) && !empty($_GET['category'])) {
    $category_slug = $_GET['category'];
    $stmt_cat = $conn->prepare("SELECT name FROM categories WHERE slug = ?");
    $stmt_cat->bind_param("s", $category_slug);
    $stmt_cat->execute();
    if ($category = $stmt_cat->get_result()->fetch_assoc()) {
        $page_title = escape($category['name']);
        $breadcrumbs[] = ['name' => $page_title, 'url' => ''];
        $page_description = "Browse " . escape($category['name']) . " listings on FexZoh. Find the best deals and connect with sellers in Nigeria.";
    }
    $stmt_cat->close();
}

$categories_result = $conn->query("SELECT id, name, slug FROM categories ORDER BY name ASC");
$categories = $categories_result->fetch_all(MYSQLI_ASSOC);

$search_query = trim($_GET['q'] ?? '');
$location_query = trim($_GET['location'] ?? '');
$category_slug_filter = trim($_GET['category'] ?? '');
$sort_by = $_GET['sort'] ?? 'newest';
?>

<!-- Page Header -->
<section class="bg-gradient-to-br from-brand-600 to-brand-700 py-8 lg:py-10" aria-labelledby="page-heading">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
                <h1 id="page-heading" class="text-2xl sm:text-3xl lg:text-4xl font-bold text-white">
                    <?php echo $page_title; ?>
                </h1>
                <p class="text-brand-100 mt-1 text-sm sm:text-base">
                    Discover amazing deals across Nigeria
                </p>
            </div>
            <a href="/user/create_ad.php" 
               class="inline-flex items-center justify-center gap-2 bg-white text-brand-600 font-semibold px-5 py-2.5 rounded-xl hover:bg-brand-50 transition-all duration-200 shadow-lg btn-hover-lift self-start sm:self-auto">
                <i data-lucide="plus-circle" class="w-5 h-5" aria-hidden="true"></i>
                <span>Post an Ad</span>
            </a>
        </div>
    </div>
</section>

<!-- Main Content -->
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-8">
    <div class="flex flex-col lg:grid lg:grid-cols-4 gap-6 lg:gap-8">
        
        <!-- Sidebar Filters -->
        <aside class="lg:col-span-1" role="complementary" aria-labelledby="filters-heading">
            <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-100 overflow-hidden lg:sticky lg:top-24">
                <!-- Mobile Filter Toggle -->
                <button id="filters-toggle" 
                        class="w-full flex items-center justify-between p-4 lg:hidden bg-gray-50 border-b border-gray-100"
                        aria-expanded="false"
                        aria-controls="filters-content"
                        aria-label="Toggle filters">
                    <div class="flex items-center gap-2">
                        <i data-lucide="sliders-horizontal" class="w-5 h-5 text-brand-600" aria-hidden="true"></i>
                        <h3 id="filters-heading" class="text-lg font-bold text-gray-900">Filters</h3>
                    </div>
                    <i data-lucide="chevron-down" id="filter-chevron" class="w-5 h-5 text-gray-500 transition-transform duration-200" aria-hidden="true"></i>
                </button>
                
                <!-- Desktop Filter Header -->
                <div class="hidden lg:flex items-center gap-2 p-5 border-b border-gray-100">
                    <i data-lucide="sliders-horizontal" class="w-5 h-5 text-brand-600" aria-hidden="true"></i>
                    <h3 class="text-lg font-bold text-gray-900">Filters</h3>
                </div>
                
                <!-- Filter Form -->
                <div id="filters-content" class="hidden lg:block p-4 lg:p-5">
                    <form id="filter-form" action="/listing.php" method="GET" class="space-y-5">
                        
                        <!-- Keyword Search -->
                        <div>
                            <label for="q" class="block text-sm font-medium text-gray-700 mb-1.5 flex items-center gap-1.5">
                                <i data-lucide="search" class="w-4 h-4 text-gray-400" aria-hidden="true"></i>
                                Keyword
                            </label>
                            <input type="text" 
                                   name="q" 
                                   id="q" 
                                   value="<?php echo escape($search_query); ?>" 
                                   placeholder="What are you looking for?"
                                   class="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200"
                                   aria-label="Search keyword">
                        </div>
                        
                        <!-- Location -->
                        <div>
                            <label for="location" class="block text-sm font-medium text-gray-700 mb-1.5 flex items-center gap-1.5">
                                <i data-lucide="map-pin" class="w-4 h-4 text-gray-400" aria-hidden="true"></i>
                                Location
                            </label>
                            <input type="text" 
                                   name="location" 
                                   id="location" 
                                   value="<?php echo escape($location_query); ?>" 
                                   placeholder="e.g., Lagos, Abuja"
                                   class="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200"
                                   aria-label="Search location">
                        </div>
                        
                        <!-- Category -->
                        <div>
                            <label for="category" class="block text-sm font-medium text-gray-700 mb-1.5 flex items-center gap-1.5">
                                <i data-lucide="grid-3x3" class="w-4 h-4 text-gray-400" aria-hidden="true"></i>
                                Category
                            </label>
                            <select name="category" 
                                    id="category" 
                                    class="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-gray-800 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200 bg-white"
                                    aria-label="Select category">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo escape($cat['slug']); ?>" <?php echo ($category_slug_filter === $cat['slug']) ? 'selected' : ''; ?>>
                                        <?php echo escape($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Price Range -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1.5 flex items-center gap-1.5">
                                <i data-lucide="tag" class="w-4 h-4 text-gray-400" aria-hidden="true"></i>
                                Price Range (₦)
                            </label>
                            <div class="flex items-center gap-3">
                                <div class="relative flex-1">
                                    <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">₦</span>
                                    <input type="number" 
                                           name="min_price" 
                                           placeholder="Min" 
                                           value="<?php echo escape($_GET['min_price'] ?? ''); ?>" 
                                           class="w-full border border-gray-200 rounded-lg pl-7 pr-3 py-2.5 text-gray-800 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200"
                                           aria-label="Minimum price">
                                </div>
                                <span class="text-gray-400">-</span>
                                <div class="relative flex-1">
                                    <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm">₦</span>
                                    <input type="number" 
                                           name="max_price" 
                                           placeholder="Max" 
                                           value="<?php echo escape($_GET['max_price'] ?? ''); ?>" 
                                           class="w-full border border-gray-200 rounded-lg pl-7 pr-3 py-2.5 text-gray-800 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200"
                                           aria-label="Maximum price">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="pt-2 space-y-3">
                            <button type="submit" 
                                    class="w-full bg-brand-600 text-white font-semibold py-3 px-4 rounded-lg hover:bg-brand-700 transition-all duration-200 flex items-center justify-center gap-2 btn-hover-lift">
                                <i data-lucide="filter" class="w-4 h-4" aria-hidden="true"></i>
                                Apply Filters
                            </button>
                            <a href="/listing.php" 
                               class="w-full block text-center py-2.5 px-4 text-sm font-medium text-gray-600 hover:text-brand-600 hover:bg-brand-50 rounded-lg transition-all duration-200">
                                Clear All Filters
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </aside>

        <!-- Results Area -->
        <main class="lg:col-span-3" role="main">
            
            <!-- Results Header -->
            <div class="bg-white p-4 sm:p-5 rounded-xl sm:rounded-2xl shadow-sm border border-gray-100 mb-4 sm:mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <p id="results-count" class="text-gray-600 flex items-center gap-2">
                    <span class="w-5 h-5 border-2 border-brand-600 border-t-transparent rounded-full animate-spin" aria-hidden="true"></span>
                    <span>Loading results...</span>
                </p>
                
                <div class="flex items-center gap-3">
                    <label for="sort-select" class="text-sm text-gray-600 hidden sm:inline">Sort by:</label>
                    <form id="sort-form" class="relative">
                        <i data-lucide="arrow-up-down" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" aria-hidden="true"></i>
                        <select name="sort" 
                                id="sort-select"
                                onchange="submitFilters()" 
                                class="pl-9 pr-10 py-2.5 border border-gray-200 rounded-lg text-gray-700 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-all duration-200 bg-white cursor-pointer appearance-none"
                                aria-label="Sort results">
                            <option value="newest" <?php echo ($sort_by === 'newest') ? 'selected' : ''; ?>>Newest First</option>
                            <option value="price_asc" <?php echo ($sort_by === 'price_asc') ? 'selected' : ''; ?>>Price: Low to High</option>
                            <option value="price_desc" <?php echo ($sort_by === 'price_desc') ? 'selected' : ''; ?>>Price: High to Low</option>
                        </select>
                        <i data-lucide="chevron-down" class="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" aria-hidden="true"></i>
                    </form>
                </div>
            </div>
            
            <!-- Items Grid -->
            <div id="items-container" class="flex gap-3 sm:gap-4 lg:gap-5">
                <div class="w-1/2 lg:w-1/3 flex-col gap-3 sm:gap-4 lg:gap-5 flex" id="item-column-1"></div>
                <div class="w-1/2 lg:w-1/3 flex-col gap-3 sm:gap-4 lg:gap-5 flex" id="item-column-2"></div>
                <div class="w-full lg:w-1/3 flex-col gap-3 sm:gap-4 lg:gap-5 hidden lg:flex" id="item-column-3"></div>
            </div>

            <!-- Loader -->
            <div id="loader" class="text-center py-8 lg:py-12" style="display: none;" aria-live="polite" aria-busy="true">
                <div class="inline-flex items-center gap-3 text-gray-500">
                    <div class="w-5 h-5 border-2 border-brand-600 border-t-transparent rounded-full animate-spin" aria-hidden="true"></div>
                    <span>Loading more items...</span>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Mobile filter toggle
    const filtersToggle = document.getElementById('filters-toggle');
    const filtersContent = document.getElementById('filters-content');
    const filterChevron = document.getElementById('filter-chevron');

    if (filtersToggle) {
        filtersToggle.addEventListener('click', function() {
            const isHidden = filtersContent.classList.contains('hidden');
            filtersContent.classList.toggle('hidden');
            filtersToggle.setAttribute('aria-expanded', (!isHidden).toString());
            filterChevron.style.transform = isHidden ? 'rotate(180deg)' : 'rotate(0deg)';
        });
    }

    let page = 1;
    let loading = false;
    let hasMoreAds = true;
    let hasMoreProducts = true;
    let itemIndex = 0;

    const loader = document.getElementById('loader');
    const resultsCount = document.getElementById('results-count');
    const filterForm = document.getElementById('filter-form');
    const sortSelect = document.querySelector('select[name="sort"]');
    const columns = [
        document.getElementById('item-column-1'),
        document.getElementById('item-column-2'),
        document.getElementById('item-column-3'),
    ];

    function getColumnCount() {
        return window.innerWidth >= 1024 ? 3 : 2;
    }

    // Escape HTML to prevent XSS
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function createItemCard(item) {
        const detailUrl = item.type === 'product' ? `/product_detail.php?id=${item.id}` : `/ad/${item.id}/${item.slug}`;
        const subHeadingInfo = item.type === 'product'
            ? `<div class="flex items-center text-xs text-gray-500 mt-1.5"><i data-lucide="store" class="h-3.5 w-3.5 mr-1.5 text-gray-400 flex-shrink-0" aria-hidden="true"></i><span class="truncate">Sold by <strong class="text-gray-700">${escapeHtml(item.seller_name)}</strong></span></div>`
            : `<div class="flex items-center text-xs text-gray-500 mt-1.5"><i data-lucide="map-pin" class="h-3.5 w-3.5 mr-1.5 text-gray-400 flex-shrink-0" aria-hidden="true"></i><span class="truncate">${escapeHtml(item.location || 'N/A')}</span></div>`;

        const promotedBadge = item.is_promoted ? '<span class="absolute top-2 left-2 bg-accent-400 text-gray-900 text-[10px] sm:text-xs font-bold px-2 py-1 rounded-md z-10 shadow-sm">Promoted</span>' : '';
        const verifiedBadge = item.is_verified ? '<span class="absolute top-2 right-2 bg-brand-100 text-brand-700 text-[10px] sm:text-xs font-semibold px-2 py-1 rounded-full flex items-center gap-1 z-10"><i data-lucide="shield-check" class="w-3 h-3" aria-hidden="true"></i> Verified</span>' : '';
        const conditionBadge = item.condition ? `<span class="px-2 py-0.5 text-[10px] sm:text-xs font-semibold rounded-full bg-gray-100 text-gray-600">${escapeHtml(item.condition)}</span>` : '';

        return `
            <article class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-100 overflow-hidden group transition-all duration-300 hover:shadow-xl hover:-translate-y-1 ${item.border_class || ''}">
                <a href="${detailUrl}" class="block" aria-label="${escapeHtml(item.title)} - ${item.price_formatted}">
                    <div class="relative">
                         <img src="/${item.thumbnail_url || 'assets/images/placeholder.png'}" 
                              alt="${escapeHtml(item.title)}" 
                              class="w-full h-auto object-cover group-hover:scale-105 transition-transform duration-300"
                              loading="lazy"
                              onerror="this.onerror=null;this.src='https://placehold.co/600x400/e2e8f0/4a5568?text=No+Image';">
                         ${promotedBadge}
                         ${verifiedBadge}
                    </div>
                    <div class="p-3 sm:p-4">
                        <h3 class="font-semibold text-sm sm:text-base text-gray-800 group-hover:text-brand-600 line-clamp-2 transition-colors duration-200">${escapeHtml(item.title)}</h3>
                        ${subHeadingInfo}
                        <div class="mt-2 sm:mt-3 flex justify-between items-center">
                            <p class="text-brand-600 font-bold text-base sm:text-lg">${item.price_formatted}</p>
                            ${conditionBadge}
                        </div>
                    </div>
                </a>
            </article>`;
    }

    async function loadItems() {
        if (loading || (!hasMoreAds && !hasMoreProducts)) return;
        loading = true;
        loader.style.display = 'block';
        loader.setAttribute('aria-busy', 'true');

        const formData = new FormData(filterForm);
        const params = new URLSearchParams(formData);
        params.set('sort', sortSelect.value);
        params.set('page', page);

        try {
            const fetchAds = hasMoreAds ? fetch(`/api/fetch_ads.php?${params.toString()}`).then(res => res.json()) : Promise.resolve({ ads: [], total_ads: 0 });
            const fetchProducts = hasMoreProducts ? fetch(`/api/fetch_products.php?${params.toString()}`).then(res => res.json()) : Promise.resolve({ items: [], total_items: 0 });
            
            const [adData, productData] = await Promise.all([fetchAds, fetchProducts]);

            if (page === 1) {
                columns.forEach(col => col.innerHTML = '');
                itemIndex = 0;
                const totalResults = (adData.total_ads || 0) + (productData.total_items || 0);
                resultsCount.innerHTML = totalResults > 0 
                    ? `Found <span class="font-semibold text-brand-600">${totalResults.toLocaleString()}</span> result${totalResults !== 1 ? 's' : ''}`
                    : 'No results found';
            }
            
            const products = (productData.items || []).map(p => ({ ...p, type: 'product' }));
            const ads = (adData.ads || []).map(a => ({ ...a, type: 'ad' }));
            let combinedItems = [...ads, ...products];

            combinedItems.sort((a, b) => {
                const sortValue = sortSelect.value;
                if (sortValue === 'price_asc') {
                    const priceA = parseFloat(a.price_formatted.replace(/[^0-9.-]+/g,""));
                    const priceB = parseFloat(b.price_formatted.replace(/[^0-9.-]+/g,""));
                    return priceA - priceB;
                }
                if (sortValue === 'price_desc') {
                    const priceA = parseFloat(a.price_formatted.replace(/[^0-9.-]+/g,""));
                    const priceB = parseFloat(b.price_formatted.replace(/[^0-9.-]+/g,""));
                    return priceB - priceA;
                }
                return new Date(b.created_at) - new Date(a.created_at);
            });

            if (combinedItems.length > 0) {
                combinedItems.forEach(item => {
                    columns[itemIndex % getColumnCount()].insertAdjacentHTML('beforeend', createItemCard(item));
                    itemIndex++;
                });
                page++;
                hasMoreAds = (adData.ads || []).length > 0;
                hasMoreProducts = (productData.items || []).length > 0;
            } else {
                hasMoreAds = false;
                hasMoreProducts = false;
                if (page === 1) {
                    const itemsContainer = document.getElementById('items-container');
                    itemsContainer.innerHTML = `
                        <div class="w-full col-span-full">
                            <div class="bg-white rounded-xl sm:rounded-2xl shadow-sm border border-gray-100 p-8 sm:p-12 text-center">
                                <div class="w-16 h-16 sm:w-20 sm:h-20 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                    <i data-lucide="search-x" class="w-8 h-8 sm:w-10 sm:h-10 text-gray-400" aria-hidden="true"></i>
                                </div>
                                <h2 class="text-xl sm:text-2xl font-bold text-gray-900 mb-2">No Items Found</h2>
                                <p class="text-gray-500 mb-6 max-w-md mx-auto">We couldn't find any items matching your search. Try adjusting your filters or search terms.</p>
                                <a href="/listing.php" class="inline-flex items-center gap-2 bg-brand-600 text-white font-semibold px-5 py-2.5 rounded-lg hover:bg-brand-700 transition-all duration-200">
                                    <i data-lucide="rotate-ccw" class="w-4 h-4" aria-hidden="true"></i>
                                    Clear Filters
                                </a>
                            </div>
                        </div>
                    `;
                }
            }

        } catch (error) {
            console.error('Error fetching items:', error);
            resultsCount.innerHTML = '<span class="text-red-600">Error loading results</span>';
        } finally {
            loading = false;
            loader.style.display = 'none';
            loader.setAttribute('aria-busy', 'false');
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        }
    }

    function submitFilters() {
        page = 1;
        hasMoreAds = true;
        hasMoreProducts = true;
        loadItems();
    }

    filterForm.addEventListener('submit', (e) => {
        e.preventDefault();
        submitFilters();
    });
    
    sortSelect.addEventListener('change', submitFilters);
    
    // Infinite scroll with Intersection Observer
    const scrollObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && !loading && (hasMoreAds || hasMoreProducts)) {
                loadItems();
            }
        });
    }, {
        rootMargin: '200px'
    });

    scrollObserver.observe(loader);

    // Fallback scroll listener
    window.addEventListener('scroll', () => {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
            loadItems();
        }
    }, { passive: true });

    // Handle window resize for column distribution
    let resizeTimeout;
    window.addEventListener('resize', () => {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(() => {
            // Redistribute items if needed
        }, 250);
    });

    // Initial load
    loadItems();
});
</script>

<?php
require_once 'includes/footer.php';
?>