<?php
/**
 * Noor-e-Libas (نورِ لباس)
 * Shop Catalog - Active Suits with Category Filter Tabs & Secondary Photo Hover
 * UI improved version
 */
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

// Category filtering parameter from GET
$typeFilter = isset($_GET['type']) ? trim($_GET['type']) : '';
$fabricFilter = isset($_GET['fabric']) ? trim($_GET['fabric']) : '';
$colorFilter = isset($_GET['color']) ? trim($_GET['color']) : '';
$collectionFilter = isset($_GET['collection']) ? trim($_GET['collection']) : '';
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'recommended';
$searchQuery = isset($_GET['q']) ? trim($_GET['q']) : '';

// Build prepared SQL query
$where = ["p.is_active = 1"];
$params = [];

if ($typeFilter) {
    $where[] = "p.type = ?";
    $params[] = $typeFilter;
}

if ($fabricFilter) {
    $where[] = "p.fabric = ?";
    $params[] = $fabricFilter;
}

if ($colorFilter) {
    $where[] = "p.color = ?";
    $params[] = $colorFilter;
}

if ($collectionFilter) {
    $where[] = "EXISTS (
        SELECT 1
        FROM product_collections pc
        INNER JOIN product_collections_catalog c ON c.id = pc.collection_id
        WHERE pc.product_id = p.id AND c.name = ? AND c.status = 'active'
    )";
    $params[] = $collectionFilter;
}

if ($searchQuery) {
    $where[] = "(p.name LIKE ? OR p.article_number LIKE ? OR p.fabric LIKE ? OR p.color LIKE ? OR p.description LIKE ?)";
    $term = "%{$searchQuery}%";
    $params[] = $term;
    $params[] = $term;
    $params[] = $term;
    $params[] = $term;
    $params[] = $term;
}

$orderBy = match ($sort) {
    'price_low_high', 'price_asc' => 'COALESCE(p.sale_price, p.price) ASC, p.id DESC',
    'price_high_low', 'price_desc' => 'COALESCE(p.sale_price, p.price) DESC, p.id DESC',
    'newest' => 'p.id DESC',
    'oldest' => 'p.id ASC',
    'best_sellers' => "(SELECT COALESCE(SUM(oi.quantity), 0)
                        FROM order_items oi
                        INNER JOIN orders o ON o.id = oi.order_id
                        WHERE oi.product_id = p.id AND o.status <> 'Cancelled') DESC, p.id DESC",
    'popular' => 'p.is_featured DESC, p.id DESC',
    default => 'p.is_featured DESC, p.id DESC'
};

$whereSql = implode(' AND ', $where);
$page = max(1, filter_var($_GET['page'] ?? 1, FILTER_VALIDATE_INT) ?: 1);
$itemsPerPage = 24;
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM products p WHERE {$whereSql}");
$countStmt->execute($params);
$totalSuits = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalSuits / $itemsPerPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $itemsPerPage;

// Query fetching main image AND secondary image for hover transition
$sql = "
    SELECT p.*,
           (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY display_order ASC, id ASC LIMIT 1) as main_image,
           (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY display_order ASC, id ASC LIMIT 1 OFFSET 1) as secondary_image
    FROM products p
    WHERE {$whereSql}
    ORDER BY {$orderBy}
    LIMIT {$itemsPerPage} OFFSET {$offset}
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();

// Dynamic product types displayed in the category track.
$typeCounts = $pdo->query("
    SELECT type, COUNT(*) AS product_count
    FROM products
    WHERE is_active = 1 AND type IS NOT NULL AND TRIM(type) <> ''
    GROUP BY type
    ORDER BY type ASC
")->fetchAll();

$allFabrics = $pdo->query("
    SELECT fabric, COUNT(*) AS product_count
    FROM products
    WHERE is_active = 1 AND fabric IS NOT NULL AND TRIM(fabric) <> ''
    GROUP BY fabric
    ORDER BY fabric ASC
")->fetchAll();
$allColors = $pdo->query("
    SELECT color, MIN(color_hex) AS color_hex, COUNT(*) AS product_count
    FROM products
    WHERE is_active = 1 AND color IS NOT NULL AND TRIM(color) <> ''
    GROUP BY color
    ORDER BY color ASC
")->fetchAll();
$allCollections = $pdo->query("
    SELECT c.name, c.group_type, c.image_path,
           (SELECT COUNT(DISTINCT pc.product_id)
            FROM product_collections pc
            INNER JOIN products p ON p.id = pc.product_id AND p.is_active = 1
            WHERE pc.collection_id = c.id) AS product_count
    FROM product_collections_catalog c
    WHERE c.status = 'active'
    ORDER BY CASE c.group_type WHEN 'collection' THEN 0 ELSE 1 END, c.sort_order ASC, c.name ASC
")->fetchAll();
$currentFilters = array_filter([
    'type' => $typeFilter,
    'fabric' => $fabricFilter,
    'color' => $colorFilter,
    'collection' => $collectionFilter,
    'q' => $searchQuery,
    'sort' => $sort !== 'recommended' ? $sort : '',
], static fn($value) => $value !== '');
$buildShopUrl = static function (array $overrides = []) use ($currentFilters): string {
    $filters = array_merge($currentFilters, $overrides);
    $filters = array_filter($filters, static fn($value) => $value !== '');
    return url('shop.php' . ($filters ? '?' . http_build_query($filters) : ''));
};

$pageTitle = ($collectionFilter ? $collectionFilter . ' Collection' : ($typeFilter ? $typeFilter . ' Suits' : 'Pakistani Unstitched Suits')) . ' | Noor-e-Libas';
$pageDescription = $collectionFilter
    ? 'Shop ' . $collectionFilter . ' Pakistani unstitched suits at Noor-e-Libas. Explore quality fabrics and designs with delivery across Pakistan.'
    : ($typeFilter
        ? 'Browse Pakistani unstitched ' . $typeFilter . ' suits at Noor-e-Libas. Shop elegant designs in quality fabrics with delivery across Pakistan.'
        : 'Browse the Noor-e-Libas collection of Pakistani unstitched 2-piece and 3-piece suits in lawn, chiffon, and seasonal fabrics.');
$pageCanonical = absoluteSiteUrl('shop');
if ($searchQuery !== '' || $fabricFilter !== '' || $colorFilter !== '' || $collectionFilter !== '' || $typeFilter !== '' || isset($_GET['sort']) || $page > 1) {
    $pageRobots = 'noindex, follow';
}

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

<section class="shop-intro">
    <div class="shop-intro-inner">
        <p class="shop-breadcrumb">
            <a href="<?= url('index.php') ?>">Home</a><span aria-hidden="true">›</span>Woman<span aria-hidden="true">›</span>Unstitched
        </p>
        <h1 class="shop-title">
            <?= $collectionFilter ? e($collectionFilter) . ' Collection' : ($typeFilter ? e($typeFilter) : ($searchQuery ? 'Search: "' . e($searchQuery) . '"' : 'Unstitched')) ?>
        </h1>

        <nav class="catalog-category-track" aria-label="Browse collections and suit types" tabindex="0">
            <a href="<?= $buildShopUrl(['collection' => '', 'type' => '', 'fabric' => '', 'color' => '']) ?>"
               class="<?= $collectionFilter === '' && $typeFilter === '' ? 'is-active' : '' ?>" <?= $collectionFilter === '' && $typeFilter === '' ? 'aria-current="page"' : '' ?>>
                View All
            </a>
            <?php foreach ($allCollections as $collectionRow): ?>
            <?php $collectionName = $collectionRow['name']; ?>
            <span class="catalog-category-track-separator" aria-hidden="true">|</span>
            <a href="<?= $buildShopUrl(['collection' => $collectionName]) ?>"
               class="<?= $collectionFilter === $collectionName ? 'is-active' : '' ?>" <?= $collectionFilter === $collectionName ? 'aria-current="page"' : '' ?>>
                <?= e($collectionName) ?>
            </a>
            <?php endforeach; ?>
            <?php foreach ($typeCounts as $typeRow): ?>
            <span class="catalog-category-track-separator" aria-hidden="true">|</span>
            <a href="<?= $buildShopUrl(['type' => $typeRow['type']]) ?>"
               class="<?= $typeFilter === $typeRow['type'] ? 'is-active' : '' ?>" <?= $typeFilter === $typeRow['type'] ? 'aria-current="page"' : '' ?>>
                <?= e($typeRow['type']) ?>
            </a>
            <?php endforeach; ?>
        </nav>

    </div>
</section>

<section class="catalog-container shop-catalog">
    <div class="filter-sort-bar">
        <div class="catalog-toolbar-actions">
            <details class="catalog-filter-disclosure" <?= ($colorFilter !== '' || $typeFilter !== '' || $fabricFilter !== '') ? 'open' : '' ?>>
                <summary>Filter <span class="catalog-disclosure-icon" aria-hidden="true"></span></summary>
                <form method="GET" action="<?= url('shop.php') ?>" class="catalog-filter-panel">
                    <?php if ($collectionFilter !== ''): ?><input type="hidden" name="collection" value="<?= e($collectionFilter) ?>"><?php endif; ?>
                    <?php if ($searchQuery !== ''): ?><input type="hidden" name="q" value="<?= e($searchQuery) ?>"><?php endif; ?>
                    <?php if ($sort !== 'recommended'): ?><input type="hidden" name="sort" value="<?= e($sort) ?>"><?php endif; ?>

                    <details class="catalog-filter-section" open>
                        <summary>Color <span class="catalog-disclosure-icon" aria-hidden="true"></span></summary>
                        <div class="catalog-color-options">
                            <label class="catalog-color-option">
                                <input type="radio" name="color" value="" <?= $colorFilter === '' ? 'checked' : '' ?>>
                                <span class="catalog-color-swatch catalog-color-swatch-all" aria-hidden="true">×</span>
                                <span>All colors</span>
                            </label>
                            <?php if (!$allColors): ?>
                            <p class="catalog-filter-empty">Color choices will appear here after colors are added to products in the admin catalog.</p>
                            <?php endif; ?>
                            <?php foreach ($allColors as $colorRow): ?>
                            <?php
                                $colorHex = preg_match('/^#[0-9A-Fa-f]{6}$/', (string)$colorRow['color_hex'])
                                    ? $colorRow['color_hex']
                                    : '#d6d3d1';
                            ?>
                            <label class="catalog-color-option">
                                <input type="radio" name="color" value="<?= e($colorRow['color']) ?>" <?= $colorFilter === $colorRow['color'] ? 'checked' : '' ?>>
                                <span class="catalog-color-swatch" style="--catalog-swatch-color: <?= e($colorHex) ?>" aria-hidden="true"></span>
                                <span><?= e($colorRow['color']) ?> <small>(<?= (int)$colorRow['product_count'] ?>)</small></span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </details>

                    <details class="catalog-filter-section" <?= $typeFilter !== '' ? 'open' : '' ?>>
                        <summary>Category <span class="catalog-disclosure-icon" aria-hidden="true"></span></summary>
                        <div class="catalog-check-options">
                            <label><input type="radio" name="type" value="" <?= $typeFilter === '' ? 'checked' : '' ?>> <span>All categories</span></label>
                            <?php foreach ($typeCounts as $typeRow): ?>
                            <label><input type="radio" name="type" value="<?= e($typeRow['type']) ?>" <?= $typeFilter === $typeRow['type'] ? 'checked' : '' ?>> <span><?= e($typeRow['type']) ?> <small>(<?= (int)$typeRow['product_count'] ?>)</small></span></label>
                            <?php endforeach; ?>
                        </div>
                    </details>

                    <details class="catalog-filter-section" <?= $fabricFilter !== '' ? 'open' : '' ?>>
                        <summary>Fabric <span class="catalog-disclosure-icon" aria-hidden="true"></span></summary>
                        <div class="catalog-check-options">
                            <label><input type="radio" name="fabric" value="" <?= $fabricFilter === '' ? 'checked' : '' ?>> <span>All fabrics</span></label>
                            <?php foreach ($allFabrics as $fabricRow): ?>
                            <label><input type="radio" name="fabric" value="<?= e($fabricRow['fabric']) ?>" <?= $fabricFilter === $fabricRow['fabric'] ? 'checked' : '' ?>> <span><?= e($fabricRow['fabric']) ?> <small>(<?= (int)$fabricRow['product_count'] ?>)</small></span></label>
                            <?php endforeach; ?>
                        </div>
                    </details>

                    <button type="submit" class="catalog-filter-submit">See Results</button>
                </form>
            </details>
            <p class="catalog-results-count">
                <?= $totalSuits ?> design<?= $totalSuits !== 1 ? 's' : '' ?>
            </p>
        </div>

        <div class="catalog-toolbar-actions catalog-toolbar-end">
            <details class="catalog-sort-disclosure" <?= isset($_GET['sort']) ? 'open' : '' ?>>
                <summary>Sort <span class="catalog-disclosure-icon" aria-hidden="true"></span></summary>
                <div class="catalog-sort-options">
                    <a href="<?= $buildShopUrl(['sort' => 'recommended']) ?>" class="<?= in_array($sort, ['recommended', 'popular'], true) ? 'is-active' : '' ?>">Recommended</a>
                    <a href="<?= $buildShopUrl(['sort' => 'best_sellers']) ?>" class="<?= $sort === 'best_sellers' ? 'is-active' : '' ?>">Best sellers</a>
                    <a href="<?= $buildShopUrl(['sort' => 'price_high_low']) ?>" class="<?= in_array($sort, ['price_high_low', 'price_desc'], true) ? 'is-active' : '' ?>">Price high to low</a>
                    <a href="<?= $buildShopUrl(['sort' => 'price_low_high']) ?>" class="<?= in_array($sort, ['price_low_high', 'price_asc'], true) ? 'is-active' : '' ?>">Price low to high</a>
                    <a href="<?= $buildShopUrl(['sort' => 'newest']) ?>" class="<?= $sort === 'newest' ? 'is-active' : '' ?>">Newest arrivals</a>
                    <a href="<?= $buildShopUrl(['sort' => 'oldest']) ?>" class="<?= $sort === 'oldest' ? 'is-active' : '' ?>">Oldest arrivals</a>
                </div>
            </details>
            <div class="catalog-view-toggles" role="group" aria-label="Product grid layout">
                <button type="button" data-catalog-columns="2" aria-label="Show two products per row" aria-pressed="false">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="8" height="16"/><rect x="13" y="4" width="8" height="16"/></svg>
                </button>
                <button type="button" data-catalog-columns="3" aria-label="Show three products per row" aria-pressed="false">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="5" height="16"/><rect x="9.5" y="4" width="5" height="16"/><rect x="16" y="4" width="5" height="16"/></svg>
                </button>
                <button type="button" data-catalog-columns="4" aria-label="Show four products per row" aria-pressed="true">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="7" height="7"/><rect x="14" y="4" width="7" height="7"/><rect x="3" y="13" width="7" height="7"/><rect x="14" y="13" width="7" height="7"/></svg>
                </button>
            </div>
        </div>
    </div>

    <?php if (empty($products)): ?>
        <div class="catalog-empty-state">
            <h2>No designs found</h2>
            <p>There are no active designs matching your current filters.</p>
            <a href="<?= url('shop.php') ?>">
                View All Suits
            </a>
        </div>
    <?php else: ?>
            <div class="catalog-products-grid" id="productGrid" data-columns="4" role="list" aria-label="Unstitched suits">
            <?php foreach ($products as $productIndex => $product): ?>
            <article class="sapphire-card" role="listitem">
                <div class="sapphire-image-container">
                <a href="<?= url('product.php?slug=' . urlencode($product['slug'])) ?>" class="sapphire-img-wrap block">
                    <img src="<?= url($product['main_image'] ?: 'uploads/sample_lawn_1.webp') ?>"
                         alt="<?= e($product['name']) ?>"
                         loading="<?= $productIndex === 0 ? 'eager' : 'lazy' ?>" decoding="async"<?= $productIndex === 0 ? ' fetchpriority="high"' : '' ?>
                         class="primary <?= !empty($product['secondary_image']) ? 'has-secondary' : '' ?>">
                    <?php if (!empty($product['secondary_image'])): ?>
                    <img src="<?= url($product['secondary_image']) ?>" loading="lazy" decoding="async"
                         alt="<?= e($product['name']) ?> Detail"
                         class="secondary">
                    <?php endif; ?>

                    <?php if (!empty($product['is_new'])): ?>
                        <span class="catalog-new-badge">New in</span>
                    <?php endif; ?>
                    <?php if (!empty($product['sale_price'])): ?>
                        <?php $discountPct = round((($product['price'] - $product['sale_price']) / $product['price']) * 100); ?>
                        <span class="catalog-sale-badge">
                            -<?= $discountPct ?>%
                        </span>
                    <?php endif; ?>

                </a>
                    <div class="sapphire-hover-bar">
                        <button type="button"
                                @click.prevent="addToCart(<?= (int)$product['id'] ?>)"
                                class="add-btn"
                                aria-label="Add <?= e($product['name']) ?> to bag">
                            Add to Bag
                        </button>
                        <button type="button" class="wish-btn" aria-label="Wishlist">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z"/>
                            </svg>
                        </button>
                    </div>
                </div>

                <div class="px-3 sm:px-4 py-4 bg-white">
                    <p class="text-[10px] uppercase tracking-[0.14em] text-stone-400 font-medium mb-1">
                        <?= e($product['type']) ?><?= !empty($product['fabric']) ? ' · ' . e($product['fabric']) : '' ?><?= !empty($product['is_new']) ? ' · New' : '' ?>
                    </p>
                    <p class="text-[10px] text-stone-500 font-mono mb-1">Article #: <?= e($product['article_number']) ?></p>
                    <h3 class="text-[12px] sm:text-[13px] font-medium uppercase tracking-[0.06em] text-stone-900 leading-snug line-clamp-2">
                        <a href="<?= url('product.php?slug=' . urlencode($product['slug'])) ?>" class="hover:text-amber-900 transition-colors">
                            <?= e($product['name']) ?>
                        </a>
                    </h3>
                    <div class="mt-2 flex items-center gap-2">
                        <?php if (!empty($product['sale_price'])): ?>
                            <span class="text-[13px] font-semibold text-stone-900"><?= formatPrice($product['sale_price']) ?></span>
                            <span class="text-[11px] text-stone-400 line-through"><?= formatPrice($product['price']) ?></span>
                        <?php else: ?>
                            <span class="text-[13px] font-semibold text-stone-900"><?= formatPrice($product['price']) ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
            <?php endforeach; ?>
            </div>
            <?php if ($totalPages > 1): ?>
            <nav class="mt-8 flex items-center justify-center gap-2" aria-label="Catalog pages">
                <?php if ($page > 1): ?>
                <a class="rounded-lg border border-stone-300 px-4 py-2 text-xs font-semibold hover:bg-stone-100"
                   href="<?= e($buildShopUrl(['page' => $page - 1])) ?>" rel="prev">Previous</a>
                <?php endif; ?>
                <span class="px-3 py-2 text-xs text-stone-600" aria-current="page">Page <?= $page ?> of <?= $totalPages ?></span>
                <?php if ($page < $totalPages): ?>
                <a class="rounded-lg border border-stone-300 px-4 py-2 text-xs font-semibold hover:bg-stone-100"
                   href="<?= e($buildShopUrl(['page' => $page + 1])) ?>" rel="next">Next</a>
                <?php endif; ?>
            </nav>
            <?php endif; ?>
    <?php endif; ?>
</section>

<script defer src="<?= e(url('assets/js/catalog-view.js')) ?>?v=<?= (int)filemtime(__DIR__ . '/assets/js/catalog-view.js') ?>"></script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
