<?php
/**
 * ============================================================================
 * marketplace/index.php - Enhanced Interactive Product Marketplace
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Marketplace';
$userId = getUserId();
$userType = getUserType();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get filters from request
$filters = [
    'category' => $_GET['category'] ?? '',
    'search' => $_GET['search'] ?? '',
    'min_price' => $_GET['min_price'] ?? '',
    'max_price' => $_GET['max_price'] ?? '',
    'location' => $_GET['location'] ?? '',
    'sort' => $_GET['sort'] ?? 'created_at',
    'order' => $_GET['order'] ?? 'DESC',
    'page' => isset($_GET['page']) ? (int)$_GET['page'] : 1,
    'per_page' => PRODUCTS_PER_PAGE
];

// Get products
$productClass = new \App\Product($db);
$products = $productClass->getAll($filters);
$totalProducts = $productClass->getCount($filters);
$totalPages = ceil($totalProducts / $filters['per_page']);

// Get categories for filter
global $PRODUCT_CATEGORIES;

// Get category counts for quick filter
$categoryCounts = [];
try {
    $sql = "SELECT category, COUNT(*) as count 
            FROM products 
            WHERE status = 'available' 
            GROUP BY category";
    $stmt = $db->query($sql);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $categoryCounts[$row['category']] = $row['count'];
    }
} catch (Exception $e) {
    logError('Category count error: ' . $e->getMessage());
}

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header with Live Search -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm bg-gradient-primary text-white">
                <div class="card-body py-4">
                    <div class="row align-items-center">
                        <div class="col-md-6 mb-3 mb-md-0">
                            <h2 class="mb-2">
                                <i class="bi bi-shop"></i> Marketplace
                            </h2>
                            <p class="mb-0 opacity-75">
                                <i class="bi bi-box-seam"></i> <?php echo number_format($totalProducts); ?> products available
                            </p>
                        </div>
                        <div class="col-md-6">
                            <!-- Live Search Bar -->
                            <div class="position-relative">
                                <input type="text" 
                                       class="form-control form-control-lg" 
                                       id="liveSearch" 
                                       placeholder="🔍 Search products..." 
                                       value="<?php echo htmlspecialchars($filters['search']); ?>">
                                <div id="searchResults" class="search-results-dropdown"></div>
                            </div>
                        </div>
                    </div>
                    <?php if ($userType === 'farmer'): ?>
                    <div class="mt-3">
                        <a href="<?php echo APP_URL; ?>/marketplace/add-product.php" 
                           class="btn btn-light btn-lg">
                            <i class="bi bi-plus-circle"></i> Sell Your Product
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Enhanced Filters Sidebar -->
        <div class="col-lg-3 mb-4">
            <div class="card border-0 shadow-sm sticky-top" style="top: 80px;">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-funnel"></i> Filters
                    </h5>
                </div>
                <div class="card-body">
                    <form method="GET" action="" id="filterForm">
                        <!-- Quick Category Chips -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Quick Categories</label>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" 
                                        class="btn btn-sm category-chip <?php echo empty($filters['category']) ? 'active' : ''; ?>" 
                                        data-category="">
                                    All
                                </button>
                                <?php foreach ($PRODUCT_CATEGORIES as $key => $cat): ?>
                                    <?php if (isset($categoryCounts[$key]) && $categoryCounts[$key] > 0): ?>
                                    <button type="button" 
                                            class="btn btn-sm category-chip <?php echo $filters['category'] === $key ? 'active' : ''; ?>" 
                                            data-category="<?php echo $key; ?>">
                                        <?php echo $cat['icon']; ?> <?php echo $cat['name']; ?>
                                        <span class="badge bg-light text-dark ms-1"><?php echo $categoryCounts[$key]; ?></span>
                                    </button>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <hr>

                        <!-- Hidden fields for search and category -->
                        <input type="hidden" name="search" id="searchInput" value="<?php echo htmlspecialchars($filters['search']); ?>">
                        <input type="hidden" name="category" id="categoryInput" value="<?php echo htmlspecialchars($filters['category']); ?>">

                        <!-- Price Range with Slider -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Price Range (UGX)
                                <small class="text-muted" id="priceRangeLabel"></small>
                            </label>
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <input type="number" 
                                           class="form-control form-control-sm" 
                                           name="min_price" 
                                           id="minPrice"
                                           placeholder="Min" 
                                           value="<?php echo htmlspecialchars($filters['min_price']); ?>">
                                </div>
                                <div class="col-6">
                                    <input type="number" 
                                           class="form-control form-control-sm" 
                                           name="max_price" 
                                           id="maxPrice"
                                           placeholder="Max" 
                                           value="<?php echo htmlspecialchars($filters['max_price']); ?>">
                                </div>
                            </div>
                        </div>

                        <!-- Location Filter -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Location</label>
                            <input type="text" 
                                   class="form-control" 
                                   name="location" 
                                   placeholder="District/Subcounty" 
                                   value="<?php echo htmlspecialchars($filters['location']); ?>">
                        </div>

                        <!-- Sort Options -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Sort By</label>
                            <select class="form-select" name="sort" id="sortSelect">
                                <option value="created_at" <?php echo $filters['sort'] === 'created_at' ? 'selected' : ''; ?>>
                                    Newest First
                                </option>
                                <option value="price_per_unit" <?php echo $filters['sort'] === 'price_per_unit' ? 'selected' : ''; ?>>
                                    Price: Low to High
                                </option>
                                <option value="views" <?php echo $filters['sort'] === 'views' ? 'selected' : ''; ?>>
                                    Most Viewed
                                </option>
                                <option value="product_name" <?php echo $filters['sort'] === 'product_name' ? 'selected' : ''; ?>>
                                    Name (A-Z)
                                </option>
                            </select>
                        </div>

                        <!-- Hidden order field -->
                        <input type="hidden" name="order" value="<?php echo $filters['order']; ?>">

                        <!-- Action Buttons -->
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-search"></i> Apply Filters
                            </button>
                            <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-outline-secondary">
                                <i class="bi bi-x-circle"></i> Clear All
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Enhanced Products Grid -->
        <div class="col-lg-9">
            <!-- Active Filters Display -->
            <?php if (!empty($filters['search']) || !empty($filters['category']) || !empty($filters['location'])): ?>
            <div class="alert alert-info alert-dismissible fade show mb-3" role="alert">
                <strong>Active Filters:</strong>
                <?php if (!empty($filters['search'])): ?>
                    <span class="badge bg-primary ms-2">Search: "<?php echo htmlspecialchars($filters['search']); ?>"</span>
                <?php endif; ?>
                <?php if (!empty($filters['category'])): ?>
                    <span class="badge bg-success ms-2">
                        <?php echo $PRODUCT_CATEGORIES[$filters['category']]['icon'] ?? ''; ?>
                        <?php echo $PRODUCT_CATEGORIES[$filters['category']]['name'] ?? $filters['category']; ?>
                    </span>
                <?php endif; ?>
                <?php if (!empty($filters['location'])): ?>
                    <span class="badge bg-warning ms-2">
                        <i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($filters['location']); ?>
                    </span>
                <?php endif; ?>
                <button type="button" class="btn-close" onclick="window.location='<?php echo APP_URL; ?>/marketplace/'"></button>
            </div>
            <?php endif; ?>

            <!-- View Toggle -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <small class="text-muted">
                        Showing <?php echo count($products); ?> of <?php echo number_format($totalProducts); ?> products
                    </small>
                </div>
                <div class="btn-group btn-group-sm" role="group">
                    <button type="button" class="btn btn-outline-secondary active" id="gridView">
                        <i class="bi bi-grid-3x3-gap"></i>
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="listView">
                        <i class="bi bi-list"></i>
                    </button>
                </div>
            </div>

            <?php if (!empty($products)): ?>
                <div class="row" id="productsContainer">
                    <?php foreach ($products as $product): ?>
                        <div class="col-sm-6 col-lg-4 mb-4 product-item">
                            <div class="card h-100 border-0 shadow-sm hover-lift product-card">
                                <!-- Product Image with Carousel -->
                                <div class="position-relative product-image-container">
                                    <?php if (!empty($product['images']) && count($product['images']) > 0): ?>
                                        <!-- Image Carousel -->
                                        <div id="carousel<?php echo $product['id']; ?>" class="carousel slide" data-bs-ride="false">
                                            <div class="carousel-inner">
                                                <?php foreach ($product['images'] as $index => $image): ?>
                                                    <div class="carousel-item <?php echo $index === 0 ? 'active' : ''; ?>">
                                                        <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>">
                                                            <img src="<?php echo APP_URL . '/' . htmlspecialchars($image); ?>" 
                                                                 class="d-block w-100 product-image" 
                                                                 alt="<?php echo htmlspecialchars($product['product_name']); ?>"
                                                                 loading="lazy"
                                                                 onerror="this.src='<?php echo APP_URL; ?>/assets/images/no-image.png'">
                                                        </a>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                            <?php if (count($product['images']) > 1): ?>
                                                <button class="carousel-control-prev" type="button" data-bs-target="#carousel<?php echo $product['id']; ?>" data-bs-slide="prev">
                                                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                                    <span class="visually-hidden">Previous</span>
                                                </button>
                                                <button class="carousel-control-next" type="button" data-bs-target="#carousel<?php echo $product['id']; ?>" data-bs-slide="next">
                                                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                                    <span class="visually-hidden">Next</span>
                                                </button>
                                                <!-- Image Indicators -->
                                                <div class="carousel-indicators">
                                                    <?php foreach ($product['images'] as $index => $image): ?>
                                                        <button type="button" 
                                                                data-bs-target="#carousel<?php echo $product['id']; ?>" 
                                                                data-bs-slide-to="<?php echo $index; ?>" 
                                                                <?php echo $index === 0 ? 'class="active"' : ''; ?>></button>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php else: ?>
                                        <!-- No Image Placeholder -->
                                        <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>">
                                            <div class="bg-light d-flex align-items-center justify-content-center product-image-placeholder">
                                                <i class="bi bi-image text-muted" style="font-size: 3rem;"></i>
                                            </div>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <!-- Category Badge -->
                                    <span class="position-absolute top-0 start-0 m-2 badge" 
                                          style="background-color: <?php echo getCategoryColor($product['category']); ?>">
                                        <?php echo $PRODUCT_CATEGORIES[$product['category']]['icon'] ?? ''; ?>
                                        <?php echo $PRODUCT_CATEGORIES[$product['category']]['name'] ?? $product['category']; ?>
                                    </span>
                                    
                                    <!-- Views Badge -->
                                    <span class="position-absolute top-0 end-0 m-2 badge bg-dark bg-opacity-75">
                                        <i class="bi bi-eye"></i> <?php echo number_format($product['views']); ?>
                                    </span>

                                    <!-- Favorite Button -->
                                    <button class="btn btn-sm btn-light position-absolute bottom-0 end-0 m-2 favorite-btn" 
                                            data-product-id="<?php echo $product['id']; ?>"
                                            title="Add to favorites">
                                        <i class="bi bi-heart"></i>
                                    </button>
                                </div>

                                <div class="card-body">
                                    <h5 class="card-title mb-2">
                                        <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                                           class="text-decoration-none text-dark stretched-link">
                                            <?php echo htmlspecialchars($product['product_name']); ?>
                                        </a>
                                    </h5>
                                    
                                    <p class="card-text text-muted small mb-2">
                                        <?php echo truncate($product['description'], 80); ?>
                                    </p>
                                    
                                    <!-- Price -->
                                    <div class="mb-2">
                                        <h4 class="text-success mb-0">
                                            <?php echo formatCurrency($product['price_per_unit']); ?>
                                            <small class="text-muted fs-6">/ <?php echo htmlspecialchars($product['unit']); ?></small>
                                        </h4>
                                    </div>
                                    
                                    <!-- Quantity -->
                                    <div class="mb-2 text-muted small">
                                        <i class="bi bi-box"></i> 
                                        <?php echo number_format($product['quantity'], 2); ?> <?php echo htmlspecialchars($product['unit']); ?> available
                                    </div>
                                    
                                    <!-- Location -->
                                    <?php if (!empty($product['location'])): ?>
                                        <div class="mb-3 text-muted small">
                                            <i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($product['location']); ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <!-- Seller Info -->
                                    <div class="d-flex align-items-center mb-3 pb-3 border-bottom">
                                        <div class="flex-shrink-0">
                                            <img src="<?php echo getAvatarUrl($product['seller_avatar'] ?? null); ?>" 
                                                 class="rounded-circle" 
                                                 width="32" height="32"
                                                 alt="Seller">
                                        </div>
                                        <div class="flex-grow-1 ms-2">
                                            <div class="small fw-semibold"><?php echo htmlspecialchars($product['seller_name']); ?></div>
                                            <?php if ($product['seller_rating']): ?>
                                                <div class="small text-warning">
                                                    <i class="bi bi-star-fill"></i> 
                                                    <?php echo number_format($product['seller_rating'], 1); ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card-footer bg-transparent border-top-0 pt-0">
                                    <div class="row g-2">
                                        <div class="col-8">
                                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                                               class="btn btn-primary btn-sm w-100">
                                                <i class="bi bi-eye"></i> View Details
                                            </a>
                                        </div>
                                        <div class="col-4">
                                            <button class="btn btn-outline-primary btn-sm w-100 share-btn" 
                                                    data-product-id="<?php echo $product['id']; ?>"
                                                    title="Share">
                                                <i class="bi bi-share"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <nav aria-label="Product pagination" class="mt-4">
                        <ul class="pagination justify-content-center">
                            <?php if ($filters['page'] > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($filters, ['page' => $filters['page'] - 1])); ?>">
                                        <i class="bi bi-chevron-left"></i> Previous
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <?php if ($i == 1 || $i == $totalPages || abs($i - $filters['page']) <= 2): ?>
                                    <li class="page-item <?php echo $i == $filters['page'] ? 'active' : ''; ?>">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($filters, ['page' => $i])); ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    </li>
                                <?php elseif (abs($i - $filters['page']) == 3): ?>
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                <?php endif; ?>
                            <?php endfor; ?>
                            
                            <?php if ($filters['page'] < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?<?php echo http_build_query(array_merge($filters, ['page' => $filters['page'] + 1])); ?>">
                                        Next <i class="bi bi-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                <?php endif; ?>

            <?php else: ?>
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">No Products Found</h4>
                        <p class="text-muted">Try adjusting your filters or search terms</p>
                        <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-primary">
                            <i class="bi bi-arrow-clockwise"></i> Clear Filters
                        </a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Enhanced CSS -->
<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}

.product-card {
    transition: all 0.3s ease;
    overflow: hidden;
}

.product-image-container {
    height: 250px;
    overflow: hidden;
    background: #f8f9fa;
}

.product-image {
    width: 100%;
    height: 250px;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.product-card:hover .product-image {
    transform: scale(1.05);
}

.product-image-placeholder {
    height: 250px;
}

.carousel-control-prev,
.carousel-control-next {
    width: 30px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.product-card:hover .carousel-control-prev,
.product-card:hover .carousel-control-next {
    opacity: 0.8;
}

.carousel-indicators {
    margin-bottom: 5px;
}

.carousel-indicators [data-bs-target] {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.category-chip {
    border: 2px solid #e5e7eb;
    background: white;
    color: #374151;
    transition: all 0.2s;
}

.category-chip:hover {
    border-color: #667eea;
    background: #f3f4f6;
    transform: translateY(-2px);
}

.category-chip.active {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

.favorite-btn {
    opacity: 0;
    transition: all 0.3s ease;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.product-card:hover .favorite-btn {
    opacity: 1;
}

.favorite-btn.active {
    background: #dc2626;
    color: white;
    opacity: 1;
}

.search-results-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    margin-top: 0.5rem;
    max-height: 400px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
    display: none;
}

.search-results-dropdown.show {
    display: block;
}

.search-result-item {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid #f3f4f6;
    cursor: pointer;
    transition: background 0.2s;
}

.search-result-item:hover {
    background: #f9fafb;
}

.search-result-item:last-child {
    border-bottom: none;
}

.sticky-top {
    position: sticky;
}

@media (max-width: 991px) {
    .sticky-top {
        position: relative;
    }
    
    .product-image-container {
        height: 200px;
    }
    
    .product-image,
    .product-image-placeholder {
        height: 200px;
    }
}

/* List View Styles */
.product-card.list-view {
    flex-direction: row;
}

.product-card.list-view .product-image-container {
    width: 200px;
    min-width: 200px;
}

.product-card.list-view .card-body {
    flex: 1;
}

/* Loading Animation */
@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

.loading {
    animation: pulse 1.5s ease-in-out infinite;
}
</style>

<!-- Enhanced JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Live Search
    let searchTimeout;
    const liveSearch = document.getElementById('liveSearch');
    const searchResults = document.getElementById('searchResults');
    const searchInput = document.getElementById('searchInput');
    
    liveSearch.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.trim();
        
        if (query.length < 2) {
            searchResults.classList.remove('show');
            return;
        }
        
        searchTimeout = setTimeout(() => {
            fetch(`<?php echo APP_URL; ?>/api/search-products.php?q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    displaySearchResults(data.products || []);
                })
                .catch(error => console.error('Search error:', error));
        }, 300);
    });
    
    function displaySearchResults(products) {
        if (products.length === 0) {
            searchResults.innerHTML = '<div class="search-result-item text-muted">No products found</div>';
            searchResults.classList.add('show');
            return;
        }
        
        let html = '';
        products.forEach(product => {
            const image = product.images && product.images.length > 0 
                ? `<?php echo APP_URL; ?>/${product.images[0]}`
                : '<?php echo APP_URL; ?>/assets/images/no-image.png';
            
            html += `
                <div class="search-result-item d-flex align-items-center" onclick="window.location='<?php echo APP_URL; ?>/marketplace/product-details.php?id=${product.id}'">
                    <img src="${image}" alt="${product.product_name}" class="rounded me-3" width="50" height="50" style="object-fit: cover;">
                    <div class="flex-grow-1">
                        <div class="fw-semibold">${product.product_name}</div>
                        <div class="small text-success">${formatCurrency(product.price_per_unit)} / ${product.unit}</div>
                    </div>
                    <div class="text-muted small">${product.category}</div>
                </div>
            `;
        });
        
        searchResults.innerHTML = html;
        searchResults.classList.add('show');
    }
    
    // Close search results when clicking outside
    document.addEventListener('click', function(e) {
        if (!liveSearch.contains(e.target) && !searchResults.contains(e.target)) {
            searchResults.classList.remove('show');
        }
    });
    
    // Category chips
    document.querySelectorAll('.category-chip').forEach(chip => {
        chip.addEventListener('click', function() {
            const category = this.dataset.category;
            document.getElementById('categoryInput').value = category;
            document.getElementById('filterForm').submit();
        });
    });
    
    // Sort change
    document.getElementById('sortSelect')?.addEventListener('change', function() {
        document.getElementById('filterForm').submit();
    });
    
    // Price range display
    const minPrice = document.getElementById('minPrice');
    const maxPrice = document.getElementById('maxPrice');
    const priceRangeLabel = document.getElementById('priceRangeLabel');
    
    function updatePriceLabel() {
        const min = minPrice.value || '0';
        const max = maxPrice.value || '∞';
        priceRangeLabel.textContent = `(${formatCurrency(min)} - ${max === '∞' ? max : formatCurrency(max)})`;
    }
    
    minPrice?.addEventListener('input', updatePriceLabel);
    maxPrice?.addEventListener('input', updatePriceLabel);
    updatePriceLabel();
    
    // View toggle
    const gridView = document.getElementById('gridView');
    const listView = document.getElementById('listView');
    const productsContainer = document.getElementById('productsContainer');
    
    listView?.addEventListener('click', function() {
        gridView.classList.remove('active');
        this.classList.add('active');
        productsContainer.classList.add('list-view');
        document.querySelectorAll('.product-card').forEach(card => {
            card.classList.add('list-view');
            card.closest('.product-item').classList.remove('col-sm-6', 'col-lg-4');
            card.closest('.product-item').classList.add('col-12');
        });
    });
    
    gridView?.addEventListener('click', function() {
        listView.classList.remove('active');
        this.classList.add('active');
        productsContainer.classList.remove('list-view');
        document.querySelectorAll('.product-card').forEach(card => {
            card.classList.remove('list-view');
            card.closest('.product-item').classList.remove('col-12');
            card.closest('.product-item').classList.add('col-sm-6', 'col-lg-4');
        });
    });
    
    // Favorite functionality
    document.querySelectorAll('.favorite-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const productId = this.dataset.productId;
            
            fetch(`<?php echo APP_URL; ?>/api/toggle-favorite.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ product_id: productId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.classList.toggle('active');
                    const icon = this.querySelector('i');
                    icon.classList.toggle('bi-heart');
                    icon.classList.toggle('bi-heart-fill');
                }
            })
            .catch(error => console.error('Favorite error:', error));
        });
    });
    
    // Share functionality
    document.querySelectorAll('.share-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const productId = this.dataset.productId;
            const url = `<?php echo APP_URL; ?>/marketplace/product-details.php?id=${productId}`;
            
            if (navigator.share) {
                navigator.share({
                    title: 'Check out this product',
                    url: url
                }).catch(() => {});
            } else {
                // Fallback: copy to clipboard
                navigator.clipboard.writeText(url).then(() => {
                    alert('Link copied to clipboard!');
                });
            }
        });
    });
    
    // Helper function
    function formatCurrency(amount) {
        return 'UGX ' + parseFloat(amount).toLocaleString('en-UG');
    }
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>