<?php
/**
 * Products Listing Page - PREMIUM VERSION
 * Digital Marketplace
 */

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

$page_title = 'Browse Products';

// Get filter parameters
$category_slug = $_GET['category'] ?? '';
$search = sanitize($_GET['search'] ?? '');
$sort = $_GET['sort'] ?? 'newest';
$min_price = $_GET['min_price'] ?? '';
$max_price = $_GET['max_price'] ?? '';

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 12;
$offset = ($page - 1) * $per_page;

// Build query options
$options = [
    'limit' => $per_page,
    'offset' => $offset,
    'sort' => $sort,
    'search' => $search ?: null
];

if ($category_slug) {
    $options['category_slug'] = $category_slug;
}

if ($min_price !== '') {
    $options['min_price'] = (float)$min_price;
}

if ($max_price !== '') {
    $options['max_price'] = (float)$max_price;
}

// Get products
$products = get_products($options);

// Get total count for pagination
$count_options = $options;
$count_options['limit'] = null;
$count_options['offset'] = 0;
$all_products = get_products($count_options);
$total_products = count($all_products);
$total_pages = ceil($total_products / $per_page);

// Get categories for filter
$categories = get_all_categories();

// Get current category info
$current_category = null;
if ($category_slug) {
    $current_category = get_category_by_slug($category_slug);
}

include __DIR__ . '/includes/header.php';
?>

<section class="section">
    <div class="container">
        <!-- Page Header -->
        <div class="page-header mb-4" data-aos="fade-up">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?php echo BASE_URL; ?>/index.php">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Products</li>
                    <?php if ($current_category): ?>
                        <li class="breadcrumb-item active" aria-current="page"><?php echo sanitize($current_category['name']); ?></li>
                    <?php endif; ?>
                </ol>
            </nav>
            
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                <h1 class="mb-0">
                    <?php if ($current_category): ?>
                        <?php echo sanitize($current_category['name']); ?>
                    <?php elseif ($search): ?>
                        Search Results: "<?php echo $search; ?>"
                    <?php else: ?>
                        All Products
                    <?php endif; ?>
                </h1>
                
                <span class="text-muted">
                    Showing <?php echo count($products); ?> of <?php echo $total_products; ?> products
                </span>
            </div>
        </div>
        
        <div class="row g-4">
            <!-- Sidebar Filters -->
            <div class="col-lg-3">
                <div class="filters-sidebar" data-aos="fade-right">
                    <!-- Mobile Filter Toggle -->
                    <button class="btn btn-primary w-100 d-lg-none mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#filtersCollapse">
                        <i class="fas fa-filter me-2"></i>Filters
                    </button>
                    
                    <div class="collapse d-lg-block" id="filtersCollapse">
                        <!-- Search -->
                        <div class="filter-card mb-4">
                            <h6 class="filter-title">Search</h6>
                            <form action="<?php echo BASE_URL; ?>/products.php" method="GET">
                                <div class="input-group">
                                    <input type="text" name="search" class="form-control" 
                                           placeholder="Search products..."
                                           value="<?php echo $search; ?>">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Categories -->
                        <div class="filter-card mb-4">
                            <h6 class="filter-title">Categories</h6>
                            <div class="filter-list">
                                <a href="<?php echo BASE_URL; ?>/products.php" 
                                   class="filter-item <?php echo !$category_slug ? 'active' : ''; ?>">
                                    <i class="fas fa-th-large me-2"></i>All Categories
                                </a>
                                <?php foreach ($categories as $cat): ?>
                                <a href="<?php echo BASE_URL; ?>/products.php?category=<?php echo $cat['slug']; ?>" 
                                   class="filter-item <?php echo $category_slug === $cat['slug'] ? 'active' : ''; ?>">
                                    <i class="fas fa-folder me-2"></i><?php echo sanitize($cat['name']); ?>
                                    <span class="badge bg-secondary ms-auto"><?php echo $cat['product_count'] ?? 0; ?></span>
                                </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Price Range -->
                        <div class="filter-card mb-4">
                            <h6 class="filter-title">Price Range</h6>
                            <form action="<?php echo BASE_URL; ?>/products.php" method="GET">
                                <?php if ($category_slug): ?>
                                    <input type="hidden" name="category" value="<?php echo $category_slug; ?>">
                                <?php endif; ?>
                                <?php if ($search): ?>
                                    <input type="hidden" name="search" value="<?php echo $search; ?>">
                                <?php endif; ?>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <input type="number" name="min_price" class="form-control" 
                                               placeholder="Min" value="<?php echo $min_price; ?>">
                                    </div>
                                    <div class="col-6">
                                        <input type="number" name="max_price" class="form-control" 
                                               placeholder="Max" value="<?php echo $max_price; ?>">
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary w-100 mt-2">
                                    <i class="fas fa-filter me-2"></i>Apply Filter
                                </button>
                            </form>
                        </div>
                        
                        <!-- Clear Filters -->
                        <?php if ($category_slug || $search || $min_price || $max_price): ?>
                        <a href="<?php echo BASE_URL; ?>/products.php" class="btn btn-outline-light w-100">
                            <i class="fas fa-times me-2"></i>Clear Filters
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Products Grid -->
            <div class="col-lg-9">
                <!-- Sort & View -->
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4" data-aos="fade-up">
                    <div class="sort-dropdown">
                        <label class="me-2 text-muted">Sort by:</label>
                        <select class="form-select d-inline-block w-auto" onchange="window.location.href=this.value">
                            <?php 
                            $base_url = BASE_URL . '/products.php?';
                            if ($category_slug) $base_url .= 'category=' . $category_slug . '&';
                            if ($search) $base_url .= 'search=' . urlencode($search) . '&';
                            if ($min_price) $base_url .= 'min_price=' . $min_price . '&';
                            if ($max_price) $base_url .= 'max_price=' . $max_price . '&';
                            ?>
                            <option value="<?php echo $base_url; ?>sort=newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest</option>
                            <option value="<?php echo $base_url; ?>sort=price_low" <?php echo $sort === 'price_low' ? 'selected' : ''; ?>>Price: Low to High</option>
                            <option value="<?php echo $base_url; ?>sort=price_high" <?php echo $sort === 'price_high' ? 'selected' : ''; ?>>Price: High to Low</option>
                            <option value="<?php echo $base_url; ?>sort=bestseller" <?php echo $sort === 'bestseller' ? 'selected' : ''; ?>>Bestsellers</option>
                            <option value="<?php echo $base_url; ?>sort=rating" <?php echo $sort === 'rating' ? 'selected' : ''; ?>>Top Rated</option>
                            <option value="<?php echo $base_url; ?>sort=popular" <?php echo $sort === 'popular' ? 'selected' : ''; ?>>Most Popular</option>
                        </select>
                    </div>
                </div>
                
                <?php if (empty($products)): ?>
                    <!-- No Products -->
                    <div class="text-center py-5" data-aos="fade-up">
                        <i class="fas fa-search fa-4x text-muted mb-4"></i>
                        <h3>No products found</h3>
                        <p class="text-muted">Try adjusting your search or filters</p>
                        <a href="<?php echo BASE_URL; ?>/products.php" class="btn btn-primary">
                            <i class="fas fa-times me-2"></i>Clear Filters
                        </a>
                    </div>
                <?php else: ?>
                    <!-- Products Grid -->
                    <div class="row g-4">
                        <?php foreach ($products as $index => $product): ?>
                        <div class="col-lg-4 col-md-6" data-aos="fade-up" data-aos-delay="<?php echo ($index % 3) * 100; ?>">
                            <div class="product-card">
                                <div class="product-image-wrapper">
                                    <img src="<?php echo get_product_image_url($product); ?>" 
                                         alt="<?php echo sanitize($product['name']); ?>"
                                         onerror="this.src='<?php echo ASSETS_URL; ?>/images/no-image.jpg'">
                                    
                                    <div class="product-badges">
                                        <?php if ($product['sale_price'] && $product['sale_price'] > 0): ?>
                                            <span class="product-badge sale">-<?php echo calculate_discount($product['price'], $product['sale_price']); ?>%</span>
                                        <?php endif; ?>
                                        <?php if ($product['featured']): ?>
                                            <span class="product-badge featured"><i class="fas fa-star"></i> Featured</span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="product-overlay">
                                        <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>" class="btn btn-primary">
                                            <i class="fas fa-eye me-2"></i>View Details
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="product-body">
                                    <div class="product-category">
                                        <i class="fas fa-tag me-1"></i><?php echo sanitize($product['category_name'] ?? 'Uncategorized'); ?>
                                    </div>
                                    <h5 class="product-title">
                                        <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>">
                                            <?php echo sanitize($product['name']); ?>
                                        </a>
                                    </h5>
                                    <p class="product-description"><?php echo sanitize(truncate($product['short_description'], 60)); ?></p>
                                    
                                    <div class="product-meta">
                                        <div class="product-rating">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <i class="fas fa-star<?php echo $i > ($product['avg_rating'] ?? 5) ? '-half-alt' : ''; ?>"></i>
                                            <?php endfor; ?>
                                            <span class="reviews">(<?php echo $product['review_count'] ?? 0; ?>)</span>
                                        </div>
                                        <div class="product-sales">
                                            <i class="fas fa-shopping-cart me-1"></i><?php echo number_format($product['times_sold'] ?? 0); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="product-price">
                                        <?php if ($product['sale_price'] && $product['sale_price'] > 0): ?>
                                            <span class="price-current"><?php echo format_price($product['sale_price']); ?></span>
                                            <span class="price-original"><?php echo format_price($product['price']); ?></span>
                                        <?php else: ?>
                                            <span class="price-current"><?php echo format_price($product['price']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="product-actions">
                                        <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $product['slug']; ?>" class="btn btn-primary">
                                            <i class="fas fa-shopping-cart me-2"></i>Add to Cart
                                        </a>
                                        <?php if (is_user_logged_in()): ?>
                                        <button class="wishlist-btn<?php echo is_in_wishlist($product['id']) ? ' active' : ''; ?>" data-product-id="<?php echo $product['id']; ?>">
                                            <i class="<?php echo is_in_wishlist($product['id']) ? 'fas' : 'far'; ?> fa-heart"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav class="mt-5" data-aos="fade-up">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $page - 1; ?>">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <?php if ($i === 1 || $i === $total_pages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                                <?php elseif ($i === $page - 3 || $i === $page + 3): ?>
                                <li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>
                                <?php endif; ?>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?php echo $base_url; ?>page=<?php echo $page + 1; ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<style>
/* Filters Sidebar */
.filters-sidebar {
    position: sticky;
    top: 100px;
}

.filter-card {
    background: var(--dark-card);
    border: 1px solid var(--dark-lighter);
    border-radius: var(--radius);
    padding: 1.5rem;
}

.filter-title {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 1rem;
    color: var(--white);
}

.filter-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.filter-item {
    display: flex;
    align-items: center;
    padding: 10px 12px;
    border-radius: var(--radius-sm);
    color: var(--gray-400);
    transition: var(--transition);
}

.filter-item:hover {
    background: var(--dark-lighter);
    color: var(--white);
    text-decoration: none;
}

.filter-item.active {
    background: var(--gradient-primary);
    color: var(--white);
}

.filter-item .badge {
    font-size: 0.75rem;
}

/* Sort Dropdown */
.sort-dropdown .form-select {
    background: var(--dark-lighter);
    border-color: var(--dark-lighter);
    color: var(--white);
}
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>
