<?php if (!defined('STORE_ROOT')) { http_response_code(403); exit; }
$products = []; $store_id = $store_id ?? 1;
try {
    $products = Database::all(
        "SELECT p.*, c.name AS cat_name FROM products p
         LEFT JOIN categories c ON c.id = p.category_id
         WHERE p.store_id = :sid AND p.status = 'active'",
        [':sid' => $store_id]
    );
} catch (\Throwable $e) { error_log('[Home] ' . $e->getMessage()); }

foreach ($products as &$p) {
    $rawName = $p['name'] ?? '';
    $p['name'] = Crypt::d($rawName) ?: Crypt::d($p['title'] ?? '') ?: $rawName;
    $p['description'] = Crypt::d($p['description'] ?? '') ?: Crypt::d($p['notes'] ?? '');
    $p['notes'] = $p['description'];
    $decPrice = Crypt::d($p['base_price'] ?? '');
    $p['base_price'] = is_numeric($decPrice) ? (float)$decPrice : (float)($p['price'] ?? 0);
    $p['price'] = $p['base_price'];
    $p['short_desc'] = Crypt::d($p['short_desc'] ?? '');

    // Variant label
    $rawVL = $p['variant_label'] ?? '';
    $p['_variantLabel'] = Crypt::d($rawVL) ?: $rawVL ?: '';

    // Load variants
    $p['_variants'] = [];
    try {
        $variants = Database::all(
            "SELECT id, quality_name, base_price, image_path, display_order, is_active
             FROM product_qualities WHERE product_id = :pid AND is_active = 1
             ORDER BY display_order",
            [':pid' => $p['id']]
        );
        foreach ($variants as &$v) {
            $v['label'] = Crypt::d($v['quality_name'] ?? '') ?: $v['quality_name'];
            $decVP = Crypt::d($v['base_price'] ?? '');
            $v['base_price'] = is_numeric($decVP) ? (float)$decVP : (float)$v['base_price'];
        }
        unset($v);
        $p['_variants'] = $variants;
    } catch (\Throwable $e) { error_log('[Home] ' . $e->getMessage()); }

    // Load sizes grouped by variant
    $p['_sizes'] = [];
    $p['_sizesByVariant'] = [];
    try {
        $sizes = Database::all(
            "SELECT id, quality_id, unit_amount, unit_price, display_order
             FROM product_units WHERE product_id = :pid
             ORDER BY quality_id, display_order",
            [':pid' => $p['id']]
        );
        foreach ($sizes as &$s) {
            $s['label'] = Crypt::d($s['unit_amount'] ?? '') ?: $s['unit_amount'];
            $decSP = Crypt::d($s['unit_price'] ?? '');
            $s['price'] = is_numeric($decSP) ? (float)$decSP : (float)$s['unit_price'];
            $vid = (int)($s['quality_id'] ?? 0);
            if ($vid > 0) {
                $p['_sizesByVariant'][$vid][] = [
                    'id' => (int)$s['id'],
                    'label' => $s['label'],
                    'price' => $s['price'],
                    'display_order' => (int)$s['display_order'],
                ];
            }
        }
        unset($s);
        $p['_sizes'] = $sizes;
    } catch (\Throwable $e) { error_log('[Home] ' . $e->getMessage()); }
}
unset($p);

// Second pass: compute display data
foreach ($products as &$p) {
    // Image fallback: product image_path → first variant's image → empty
    $img = '';
    $rawImgPath = $p['image'] ?? $p['image_path'] ?? '';
    if (strpos($rawImgPath, '..') !== false || preg_match('#^https?://#i', $rawImgPath)) { $rawImgPath = '/assets/img/placeholder.png'; }
    if ($rawImgPath && $rawImgPath !== 'NULL') {
        $img = '/' . ltrim($rawImgPath, '/');
    }
    // If no product-level image, use first variant's image
    if (!$img && !empty($p['_variants'])) {
        foreach ($p['_variants'] as $v) {
            if (!empty($v['image_path'])) {
                $vip = $v['image_path'];
                if (strpos($vip, '..') !== false || preg_match('#^https?://#i', $vip)) { $vip = '/assets/img/placeholder.png'; }
                $img = '/' . ltrim($vip, '/');
                break;
            }
        }
    }
    $p['_img'] = $img;
    $variants = $p['_variants'];
    $basePrice = (float)$p['base_price'];

    // First variant's sizes for initial price
    $firstVId = !empty($variants) ? (int)$variants[0]['id'] : 0;
    $firstVSizes = $p['_sizesByVariant'][$firstVId] ?? [];

    if (!empty($firstVSizes)) {
        $activePrice = (float)$firstVSizes[0]['price'];
    } elseif (!empty($variants)) {
        $activePrice = (float)$variants[0]['base_price'];
    } else {
        $activePrice = $basePrice;
    }
    if ($activePrice <= 0) $activePrice = $basePrice;
    $p['_activePrice'] = $activePrice;

    // Image map
    $vImgs = [];
    foreach ($variants as $v) {
        $vip2 = $v['image_path'] ?? '';
        if ($vip2 && (strpos($vip2, '..') !== false || preg_match('#^https?://#i', $vip2))) { $vip2 = '/assets/img/placeholder.png'; }
        $vi = $vip2 ? '/' . ltrim($vip2, '/') : '';
        $vImgs[$v['id']] = $vi ?: $img;
    }
    $p['_vImgs'] = $vImgs;

}
unset($p);

// Third pass: Sort everything after decrypting display_order
usort($products, function($a, $b) {
    $orderA = Crypt::d($a['display_order'] ?? '') ?: $a['display_order'];
    $orderB = Crypt::d($b['display_order'] ?? '') ?: $b['display_order'];
    $orderA = is_numeric($orderA) ? (int)$orderA : 0;
    $orderB = is_numeric($orderB) ? (int)$orderB : 0;
    if ($orderA !== $orderB) return $orderA <=> $orderB;
    return $a['id'] <=> $b['id'];
});

foreach ($products as &$p) {
    if (!empty($p['_variants'])) {
        usort($p['_variants'], function($a, $b) {
            $oa = Crypt::d($a['display_order'] ?? '') ?: $a['display_order'];
            $ob = Crypt::d($b['display_order'] ?? '') ?: $b['display_order'];
            $oa = is_numeric($oa) ? (int)$oa : 0;
            $ob = is_numeric($ob) ? (int)$ob : 0;
            if ($oa !== $ob) return $oa <=> $ob;
            return $a['id'] <=> $b['id'];
        });
    }
    if (!empty($p['_sizesByVariant'])) {
        foreach ($p['_sizesByVariant'] as $vid => &$sizes) {
            usort($sizes, function($a, $b) {
                $oa = Crypt::d($a['display_order'] ?? '') ?: $a['display_order'];
                $ob = Crypt::d($b['display_order'] ?? '') ?: $b['display_order'];
                $oa = is_numeric($oa) ? (int)$oa : 0;
                $ob = is_numeric($ob) ? (int)$ob : 0;
                if ($oa !== $ob) return $oa <=> $ob;
                return $a['id'] <=> $b['id'];
            });
        }
        unset($sizes);
    }
}
unset($p);
?>
<div class="page-banner sf-page-banner">
    <img src="/uploads/banners/store.png" alt="" class="sf-page-banner-bg">
    <div class="sf-page-banner-content">
        <div class="page-banner-icon">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
        </div>
        <div class="page-banner-text">
            <h2><?= $L('home_banner_title', $store_name) ?></h2>
            <p><?= $L('home_banner_sub', $store_tagline ?: 'Browse our curated product catalog') ?></p>
        </div>
    </div>
</div>
<div id="cat-nav-slot"></div>
<div class="sf-storefront" id="page-home">
    <?php if (empty($products)): ?>
    <div class="sf-coming-soon">
        <h2><?= $L('home_launching_title', 'Store Launching Soon') ?></h2>
        <p><?= $L('home_launching_desc', 'We are preparing our product catalog. Check back shortly.') ?></p>
    </div>
    <?php else: ?>
    <?php foreach ($products as $p):
        $img = $p['_img'];
        $variants = $p['_variants'];
        $vImgs = $p['_vImgs'];
        $basePrice = (float)$p['base_price'];
        $activePrice = $p['_activePrice'];
        $sizesByVariant = $p['_sizesByVariant'];
        $variantLabel = $p['_variantLabel'];
        $firstVId = !empty($variants) ? (int)$variants[0]['id'] : 0;
        $currentSizes = $sizesByVariant[$firstVId] ?? [];
        if (empty($currentSizes) && !empty($p['_sizes'])) {
            foreach ($p['_sizes'] as $s) {
                $currentSizes[] = ['id' => (int)$s['id'], 'label' => $s['label'], 'price' => $s['price'], 'display_order' => (int)$s['display_order']];
            }
        }
    ?>
    <div class="category-section" data-category="p<?= $p['id'] ?>" data-nav="1">
        <h3 class="category-title"><?= htmlspecialchars($p['name']) ?></h3>
        <div class="sf-products-list">
        <div class="product-row-wrap">
            <div class="product-card" data-product-id="<?= $p['id'] ?>"
                 data-base-price="<?= $basePrice ?>"
                 data-variant-images="<?= htmlspecialchars(json_encode($vImgs)) ?>"
                 data-sizes-by-variant="<?= htmlspecialchars(json_encode($sizesByVariant)) ?>">
                <div class="pc-col-image">
                    <?php if ($img): ?>
                    <img class="pc-main-img" src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($p['name']) ?>">
                    <?php else: ?>
                    <div class="pc-img-placeholder"><?= strtoupper(substr($p['name'], 0, 2)) ?></div>
                    <?php endif; ?>
                </div>
                <div class="pc-col-info">
                    <div class="pc-info-header">
                        <span class="pc-info-name"><?= htmlspecialchars($p['name']) ?></span>
                        <span class="pc-info-price" data-unit-price="<?= $activePrice ?>">$<?= number_format($activePrice, 2) ?></span>
                    </div>
                    <hr class="pc-info-rule">
                    <?php if (!empty($p['description'])): ?>
                    <p class="pc-desc"><?= htmlspecialchars($p['description']) ?></p>
                    <?php endif; ?>
                </div>
                <div class="pc-col-controls">
                    <?php if (!empty($variants)): ?>
                    <div class="pc-selector">
                        <label class="pc-selector-label"><?= htmlspecialchars($variantLabel ?: $L('home_variant_label', 'SELECT')) ?></label>
                        <div class="pc-pills" data-group="variant">
                            <?php foreach ($variants as $i => $v): ?>
                            <button class="pc-pill<?= $i === 0 ? ' active' : '' ?>" data-id="<?= $v['id'] ?>" data-price="<?= (float)$v['base_price'] ?>"><?= htmlspecialchars($v['label']) ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($currentSizes)): ?>
                    <div class="pc-selector">
                        <label class="pc-selector-label"><?= $L('home_packaging_label', 'PACKAGING') ?></label>
                        <div class="pc-pills" data-group="size">
                            <?php foreach ($currentSizes as $i => $s): ?>
                            <button class="pc-pill<?= $i === 0 ? ' active' : '' ?>" data-id="<?= $s['id'] ?>" data-price="<?= (float)$s['price'] ?>"><?= htmlspecialchars($s['label']) ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="pc-selector">
                        <label class="pc-selector-label"><?= $L('home_quantity_label', 'QUANTITY') ?></label>
                        <div class="pc-qty-row">
                            <button class="pc-qty-btn" data-dir="minus">−</button>
                            <span class="pc-qty-val" data-unit="<?= htmlspecialchars($p['unit_label'] ?? '') ?>">1<?php if (!empty($p['unit_label'])): ?> <small class="pc-qty-unit"><?= htmlspecialchars($p['unit_label']) ?></small><?php endif; ?></span>
                            <button class="pc-qty-btn" data-dir="plus">+</button>
                        </div>
                    </div>
                    <button class="pc-btn-cart" data-action="add-cart" data-id="<?= $p['id'] ?>"><svg class="cart-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4H6zM3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg> <?= $L('home_add_to_cart', 'Add to Cart') ?></button>
                </div>
            </div>
        </div>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>
<script src="/assets/js/category-nav.js"></script>