<?php
require_once __DIR__ . '/functions.php';
$page_title = 'Products';
$db = db();

$where = "p.is_active = 1";
$params = [];

// Search
if (!empty($_GET['q'])) {
    $where .= " AND (p.name LIKE ? OR p.description LIKE ?)";
    $q = '%' . $_GET['q'] . '%';
    array_push($params, $q, $q);
}

// Category filter
$currentCategory = null;
if (!empty($_GET['category'])) {
    $stmt = $db->prepare("SELECT * FROM categories WHERE slug = ?");
    $stmt->execute([$_GET['category']]);
    $currentCategory = $stmt->fetch();
    if ($currentCategory) {
        $where .= " AND (p.category_id = ? OR p.category_id IN (SELECT id FROM categories WHERE parent_id = ?))";
        array_push($params, $currentCategory['id'], $currentCategory['id']);
    }
}

// Sort
$order = "p.created_at DESC";
if (!empty($_GET['sort'])) {
    switch ($_GET['sort']) {
        case 'price_asc': $order = "p.price ASC"; break;
        case 'price_desc': $order = "p.price DESC"; break;
        case 'name': $order = "p.name ASC"; break;
        case 'newest': $order = "p.created_at DESC"; break;
        case 'popular': $order = "review_count DESC"; break;
    }
}

// Count total
$countSql = "SELECT COUNT(*) FROM products p WHERE $where";
$totalProducts = $db->query($countSql, $params)->fetchColumn();

// Pagination
$perPage = 12;
$page = max(1, (int)($_GET['p'] ?? 1));
$offset = ($page - 1) * $perPage;
$totalPages = ceil($totalProducts / $perPage);

// Fetch products
$sql = "SELECT p.*, 
               (SELECT image_path FROM product_images WHERE product_id = p.id AND is_primary = 1 LIMIT 1) as image,
               (SELECT ROUND(AVG(rating), 1) FROM reviews WHERE product_id = p.id AND is_approved = 1) as avg_rating,
               (SELECT COUNT(*) FROM reviews WHERE product_id = p.id AND is_approved = 1) as review_count,
               c.name as category_name
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id
        WHERE $where 
        ORDER BY $order 
        LIMIT $perPage OFFSET $offset";
$products = $db->query($sql, $params)->fetchAll();

// All categories for sidebar
$categories = $db->query("SELECT * FROM categories WHERE parent_id IS NULL AND is_active = 1 ORDER BY sort_order")->fetchAll();

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

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">
                <?php if ($currentCategory): ?>
                    <?= h($currentCategory['name']) ?>
                <?php elseif (!empty($_GET['q'])): ?>
                    Search: "<?= h($_GET['q']) ?>"
                <?php else: ?>
                    All Products
                <?php endif; ?>
            </h1>
            <p class="text-sm text-gray-500 mt-1"><?= $totalProducts ?> product(s) found</p>
        </div>
        <form method="GET" class="flex items-center gap-2">
            <?php if (!empty($_GET['category'])): ?>
            <input type="hidden" name="category" value="<?= h($_GET['category']) ?>">
            <?php endif; ?>
            <?php if (!empty($_GET['q'])): ?>
            <input type="hidden" name="q" value="<?= h($_GET['q']) ?>">
            <?php endif; ?>
            <select name="sort" onchange="this.form.submit()" class="border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500">
                <option value="newest" <?= ($_GET['sort'] ?? '') === 'newest' ? 'selected' : '' ?>>Newest</option>
                <option value="popular" <?= ($_GET['sort'] ?? '') === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                <option value="price_asc" <?= ($_GET['sort'] ?? '') === 'price_asc' ? 'selected' : '' ?>>Price: Low to High</option>
                <option value="price_desc" <?= ($_GET['sort'] ?? '') === 'price_desc' ? 'selected' : '' ?>>Price: High to Low</option>
                <option value="name" <?= ($_GET['sort'] ?? '') === 'name' ? 'selected' : '' ?>>Name</option>
            </select>
        </form>
    </div>

    <div class="flex gap-8">
        <!-- Sidebar Filters -->
        <aside class="w-56 shrink-0 hidden md:block">
            <h3 class="font-semibold text-gray-800 mb-3">Categories</h3>
            <ul class="space-y-1">
                <li><a href="catalog.php" class="block text-sm <?= !$currentCategory ? 'text-primary-600 font-medium' : 'text-gray-600 hover:text-primary-600' ?>">All Categories</a></li>
                <?php foreach ($categories as $cat): ?>
                <li><a href="catalog.php?category=<?= h($cat['slug']) ?>" class="block text-sm <?= $currentCategory && $currentCategory['id'] === $cat['id'] ? 'text-primary-600 font-medium' : 'text-gray-600 hover:text-primary-600' ?>"><?= h($cat['name']) ?></a></li>
                <?php endforeach; ?>
            </ul>
        </aside>

        <!-- Product Grid -->
        <div class="flex-1">
            <?php if (count($products) === 0): ?>
            <div class="text-center py-12">
                <i class="fas fa-box-open text-gray-300 text-5xl mb-4"></i>
                <h3 class="text-lg font-semibold text-gray-800">No products found</h3>
                <p class="text-gray-500 mt-1">Try adjusting your search or filters.</p>
            </div>
            <?php else: ?>
            <div class="grid grid-cols-2 md:grid-cols-3 gap-6">
                <?php foreach ($products as $product): ?>
                <a href="product.php?slug=<?= h($product['slug']) ?>" class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition group">
                    <div class="aspect-square bg-gray-100 flex items-center justify-center overflow-hidden relative">
                        <?php if ($product['image']): ?>
                        <img src="<?= h($product['image']) ?>" alt="<?= h($product['name']) ?>" class="w-full h-full object-cover group-hover:scale-105 transition">
                        <?php else: ?>
                        <i class="fas fa-box text-gray-300 text-5xl"></i>
                        <?php endif; ?>
                        <?php
                        $isDeal = ($product['deal_start'] ?? null) && ($product['deal_end'] ?? null) && $product['deal_start'] <= date('Y-m-d H:i:s') && $product['deal_end'] >= date('Y-m-d H:i:s');
                        if ($isDeal): ?>
                        <span class="absolute top-2 left-2 bg-red-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-sm uppercase tracking-wide">Limited time deal</span>
                        <?php endif; ?>
                        <?php if ($product['compare_price'] > $product['price']): ?>
                        <span class="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full">-<?= round((1 - $product['price'] / $product['compare_price']) * 100) ?>%</span>
                        <?php endif; ?>
                    </div>
                    <div class="p-4">
                        <p class="text-xs text-gray-500 uppercase tracking-wide"><?= h($product['category_name']) ?></p>
                        <h3 class="font-semibold text-gray-800 text-sm group-hover:text-primary-600 mt-1"><?= h($product['name']) ?></h3>
                        <div class="flex items-center gap-2 mt-2">
                            <span class="text-lg font-bold text-primary-600"><?= formatPrice($product['price']) ?></span>
                            <?php if ($product['compare_price'] > $product['price']): ?>
                            <span class="text-sm text-gray-400 line-through"><?= formatPrice($product['compare_price']) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if ($product['avg_rating']): ?>
                        <div class="flex items-center gap-1 mt-1">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                            <i class="fas fa-star text-xs <?= $i <= round($product['avg_rating']) ? 'text-yellow-400' : 'text-gray-200' ?>"></i>
                            <?php endfor; ?>
                            <span class="text-xs text-gray-500 ml-1">(<?= $product['review_count'] ?>)</span>
                        </div>
                        <?php endif; ?>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="flex items-center justify-center gap-2 mt-8">
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['p' => $i])) ?>" class="px-3 py-1.5 rounded-lg text-sm font-medium <?= $i === $page ? 'bg-primary-600 text-white' : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50' ?>"><?= $i ?></a>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

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