<?php
/**
 * product/index.php
 * Public product details page.
 */
require_once __DIR__ . '/../include/bootstrap.php';
require_once __DIR__ . '/../services/ProductService.php';

$pdo = get_db_connection();
$productService = new ProductService($pdo);

// Get the slug from the URL parameters
$slugPart = $_GET['slug'] ?? '';

if (empty($slugPart)) {
    http_response_code(404);
    include __DIR__ . '/../404.php';
    exit;
}

// Reconstruct the full slug as stored in the database
$fullSlug = '/product/' . $slugPart;
$product = $productService->getBySlug($fullSlug);

if (!$product) {
    http_response_code(404);
    include __DIR__ . '/../404.php';
    exit;
}

// Fetch Related Products
$relatedProducts = $productService->getRelatedProducts($product['id'], $product['category_id'], $product['shop_id'] ?? null, 4);

// If viewing within a shop context, update related product URLs to stay within the shop
if (isset($context_shop_slug)) {
    foreach ($relatedProducts as &$rp) {
        if (isset($rp['slug'])) {
            $rpPureSlug = ltrim(str_replace('/product/', '', $rp['slug']), '/');
            $rp['slug'] = "shop/{$context_shop_slug}/product/{$rpPureSlug}";
        }
    }
    unset($rp);
}

// Pricing logic
$price = (float)$product['price'];
$discountPrice = (float)$product['discount_price'];
$finalPrice = (float)$product['final_price'];
$hasDiscount = ($discountPrice > 0 && $discountPrice < $price);

// SEO Logic
$seo = $product['seo_meta_json'] ? (is_string($product['seo_meta_json']) ? json_decode($product['seo_meta_json'], true) : $product['seo_meta_json']) : [];
$meta_title = !empty($seo['title']) ? $seo['title'] : ($product['product_name'] . ' - Buy Online');
$meta_description = !empty($seo['description']) ? $seo['description'] : ($product['short_description'] ?? '');
$meta_keywords = !empty($seo['keywords']) ? $seo['keywords'] : '';
$custom_meta = !empty($seo['custom_tags']) ? $seo['custom_tags'] : [];
$og_image = $product['thumbnail'];
$og_type = 'product';
$og_price_amount = $finalPrice;
$og_price_currency = getSetting('currency_code', 'BDT');
$og_availability = ((int)($product['stock_quantity'] ?? 0) > 0 || (int)($product['manage_stock'] ?? 0) === 0) ? 'in stock' : 'out of stock';
$meta_robots = "index, follow";

// Product Data Preparation
$productName = $product['product_name'];
$categoryName = $product['category_name'];
$parentCategorySlug = $product['parent_category_slug'] ?? '';
$breadcrumbCategoryUrl = BASE_URL . 'category/' . (!empty($parentCategorySlug) ? $parentCategorySlug . '/' : '') . ($product['category_slug'] ?? '');
$shopName = $product['shop_name'] ?? '';
$shopSlug = $product['shop_slug'] ?? '';
$shopUrl = !empty($shopSlug) ? BASE_URL . ltrim($shopSlug, '/') : '#';
$images = $product['images'] ?? [];
$thumbnail = $product['thumbnail'] ?? 'assets/img/no-image.png';
$variants = $product['variants'] ?? [];
$specifications = $product['specifications_json'] ? (is_string($product['specifications_json']) ? json_decode($product['specifications_json'], true) : $product['specifications_json']) : [];

$page_title = $productName;
include __DIR__ . '/../include/header.php';
?>

<main class="main product-details-page">
    <div class="container py-5">
        <!-- Breadcrumbs -->
        <nav aria-label="breadcrumb" class="mb-5">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= BASE_URL ?>" class="text-decoration-none">Home</a></li>
                <?php if (isset($context_shop_slug) && !empty($shopName)): ?>
                    <li class="breadcrumb-item"><a href="<?= BASE_URL ?>shop/<?= $context_shop_slug ?>" class="text-decoration-none"><?= htmlspecialchars($shopName) ?></a></li>
                <?php else: ?>
                    <li class="breadcrumb-item"><a href="<?= $breadcrumbCategoryUrl ?>" class="text-decoration-none"><?= htmlspecialchars($categoryName ?? '') ?></a></li><?php endif; ?>
                <li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars($productName) ?></li>
            </ol>
        </nav>

        <div class="row g-5">
            <!-- Product Images -->
            <div class="col-lg-6">
                <div class="product-gallery">
                    <div class="main-image-wrapper mb-3 border rounded-4 overflow-hidden shadow-sm bg-white position-relative" style="aspect-ratio: 1/1; display: flex; align-items: center; justify-content: center;">
                        <img id="main-product-img" src="<?= BASE_URL . $thumbnail ?>" class="img-fluid" alt="<?= htmlspecialchars($productName) ?>" style="max-height: 100%; width: auto; object-fit: contain;">
                    </div>
                    <?php if (count($images) > 1): ?>
                        <div class="row g-3 thumbnail-list mt-3">
                            <?php foreach ($images as $index => $img): ?>
                                <div class="col-3">
                                    <div class="thumb-item border rounded-3 overflow-hidden cursor-pointer <?= $index === 0 ? 'active' : '' ?>" onclick="updateMainImage('<?= BASE_URL . $img ?>', this)" style="aspect-ratio: 1/1; display: flex; align-items: center; justify-content: center; background: #fff;">
                                        <img src="<?= BASE_URL . $img ?>" class="img-fluid" alt="Thumbnail <?= $index + 1 ?>" style="max-height: 100%; width: auto; object-fit: contain; padding: 5px;">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Product Info -->
            <div class="col-lg-6">
                <div class="product-info ps-lg-4">
                    <div class="mb-3 d-flex flex-wrap align-items-center gap-2">
                        <span class="badge bg-light text-primary border border-primary-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em;"><?= htmlspecialchars($categoryName ?? '') ?></span>
                        <?php if (!empty($shopName)): ?>
                            <a href="<?= $shopUrl ?>" class="text-decoration-none">
                                <span class="badge bg-light text-secondary border border-secondary-subtle px-3 py-2 rounded-pill fw-bold" style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em;">
                                    <i class="bi bi-shop me-1"></i><?= htmlspecialchars($shopName) ?>
                                </span>
                            </a>
                        <?php endif; ?>

                        <?php if ($product['isFeatured']): ?>
                            <span class="badge bg-warning text-dark px-3 py-2 rounded-pill fw-bold" style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em;">Featured</span>
                        <?php endif; ?>
                    </div>

                    <h1 class="h2 fw-bold mb-3 text-dark"><?= htmlspecialchars($productName) ?></h1>

                    <div class="product-rating mb-4 d-flex align-items-center gap-2">
                        <div class="text-warning">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="bi bi-star<?= ($i <= round($product['avg_rating'])) ? '-fill' : '' ?>"></i>
                            <?php endfor; ?>
                        </div>
                        <span class="text-muted small">(<?= $product['total_reviews'] ?> reviews)</span>
                        <span class="text-muted mx-2">|</span>
                        <span class="text-muted small"><strong>SKU:</strong> <?= htmlspecialchars($product['sku'] ?? 'N/A') ?></span>
                    </div>

                    <div class="product-price mb-4 pb-4 border-bottom">
                        <?php if ($hasDiscount): ?>
                            <div class="d-flex align-items-center gap-3">
                                <h2 class="current-price text-primary fw-bold mb-0"><?= number_format($finalPrice, 2) ?> BDT</h2>
                                <span class="text-muted text-decoration-line-through fs-5"><?= number_format($price, 2) ?> BDT</span>
                                <span class="badge bg-danger rounded-pill px-3">Save <?= round((($price - $discountPrice) / $price) * 100) ?>%</span>
                            </div>
                        <?php else: ?>
                            <h2 class="current-price text-primary fw-bold mb-0"><?= number_format($price, 2) ?> BDT</h2>
                        <?php endif; ?>
                    </div>

                    <div class="product-short-description text-muted mb-4 fs-5 lh-base">
                        <?= nl2br(htmlspecialchars($product['short_description'])) ?>
                    </div>

                    <!-- Variants -->
                    <?php
$hasRealVariants = false;
if (!empty($variants)) {
    foreach ($variants as $v) {
        $vAttrs = $v['attributes'] ?? [['key' => $v['key'] ?? '', 'value' => $v['value'] ?? '']];
        foreach ($vAttrs as $a) {
            if (!empty($a['key']) || !empty($a['value'])) {
                $hasRealVariants = true;
                break 2;
            }
        }
    }
}
?>

<?php if ($hasRealVariants): ?>
    <div class="product-options mb-4" id="product-options">
        <div id="variant-groups-container"></div>
    </div>
<?php endif; ?>

<!-- Embed variants data for JS cross-referencing (always present, empty array for simple products) -->
<script id="product-variants-data" type="application/json"><?= json_encode($variants) ?></script>

<script>
    window.defaultVariant = null;
    var variantsData = <?= json_encode($variants) ?>;
</script>

                    <div class="product-stock-status mb-4">
                        <div class="d-flex align-items-center gap-2">
                            <div class="stock-dot <?= $product['stock_qty'] > 0 ? 'bg-success' : 'bg-danger' ?>" style="width: 10px; height: 10px; border-radius: 50%;"></div>
                            <span id="stock-status-text" class="fw-bold <?= $product['stock_qty'] > 0 ? 'text-success' : 'text-danger' ?>">
                                <?= $product['stock_qty'] > 0 ? 'In Stock (' . $product['stock_qty'] . ' units available)' : 'Out of Stock' ?>
                            </span>
                        </div>
                    </div>

                    <div class="product-actions d-flex flex-wrap gap-3 mt-4 pt-2">
                        <div class="quantity-control d-flex align-items-center border rounded-pill px-2 bg-light shadow-sm" style="width: 150px; height: 50px;">
                            <button type="button" class="btn btn-link text-dark text-decoration-none px-2 qty-btn" data-delta="-1"><i class="bi bi-dash-lg"></i></button>
                            <input type="text" id="product-qty" class="form-control border-0 bg-transparent text-center fw-bold fs-5 p-0" value="1" max="<?= $product['stock_qty'] ?>" readonly style="width: 50px; box-shadow: none;">
                            <button type="button" class="btn btn-link text-dark text-decoration-none px-2 qty-btn" data-delta="1"><i class="bi bi-plus-lg"></i></button>
                        </div>
                        <input type="hidden" id="selected-variant-slug" value="">
                        <button class="btn btn-primary rounded-pill px-5 fw-bold shadow btn-main-add flex-grow-1"
                                style="height: 50px;"
                                data-id="<?= $product['id'] ?>"
                                data-name="<?= htmlspecialchars($productName) ?>"
                                data-shop-id="<?= $product['shop_id'] ?? 1 ?>">
                            <i class="bi bi-bag-plus me-2"></i>Add to Cart
                        </button>
                    </div>

                    <div class="mt-5 p-4 rounded-4 bg-light border border-white shadow-sm">
                        <div class="row g-3">
                            <div class="col-sm-6 d-flex align-items-center gap-3">
                                <div class="d-flex align-items-center justify-content-center bg-white rounded-circle shadow-sm" style="width: 48px; height: 48px; flex-shrink: 0;">
                                    <i class="bi bi-truck text-primary fs-4"></i>
                                </div>
                                <div>
                                    <div class="fw-bold text-dark small" style="font-size: 0.85rem;">Fast Delivery</div>
                                    <div class="text-muted extra-small" style="font-size: 0.72rem;">2-3 business days</div>
                                </div>
                            </div>
                            <div class="col-sm-6 d-flex align-items-center gap-3">
                                <div class="d-flex align-items-center justify-content-center bg-white rounded-circle shadow-sm" style="width: 48px; height: 48px; flex-shrink: 0;">
                                    <i class="bi bi-shield-check text-primary fs-4"></i>
                                </div>
                                <div>
                                    <div class="fw-bold text-dark small" style="font-size: 0.85rem;">Safe Payment</div>
                                    <div class="text-muted extra-small" style="font-size: 0.72rem;">100% secure checkout</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Tabs -->
        <div class="product-tabs mt-5 pt-4">
            <ul class="nav nav-pills border-bottom pb-0 gap-3 mb-5 justify-content-center" id="productTab" role="tablist" style="border-width: 2px !important;">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active fw-bold position-relative px-4 py-3" id="description-tab" data-bs-toggle="tab" data-bs-target="#description-tab-pane" type="button" role="tab">
                        <i class="bi bi-card-text me-2"></i>OVERVIEW
                    </button>
                </li>
                <?php if (!empty($specifications)): ?>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link fw-bold position-relative px-4 py-3" id="specs-tab" data-bs-toggle="tab" data-bs-target="#specs-tab-pane" type="button" role="tab">
                            <i class="bi bi-list-check me-2"></i>SPECIFICATIONS
                        </button>
                    </li>
                <?php endif; ?>
                <li class="nav-item" role="presentation">
                    <button class="nav-link fw-bold position-relative px-4 py-3" id="reviews-tab" data-bs-toggle="tab" data-bs-target="#reviews-tab-pane" type="button" role="tab">
                        <i class="bi bi-star me-2"></i>REVIEWS (<?= $product['total_reviews'] ?>)
                    </button>
                </li>
            </ul>
            <div class="tab-content" id="productTabContent">
                <div class="tab-pane fade show active" id="description-tab-pane" role="tabpanel" tabindex="0">
                    <div class="rich-text-content mx-auto" style="max-width: 900px;">
                        <?= $product['long_description'] ?: nl2br(htmlspecialchars($product['short_description'])) ?>
                    </div>
                </div>
                <?php if (!empty($specifications)): ?>
                    <div class="tab-pane fade" id="specs-tab-pane" role="tabpanel" tabindex="0">
                        <div class="mx-auto" style="max-width: 800px;">
                            <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <tbody>
                                        <?php foreach ($specifications as $label => $value): ?>
                                            <?php if (is_array($value)): ?>
                                                <?php if (isset($value['attribute'])): ?>
                                                    <tr>
                                                        <th class="ps-4 py-3 bg-light text-muted small text-uppercase" style="width: 250px;"><?= htmlspecialchars($value['attribute']) ?></th>
                                                        <td class="ps-4 py-3 fw-medium"><?= htmlspecialchars(is_array($value['value'] ?? '') ? implode(', ', $value['value']) : ($value['value'] ?? '')) ?></td>
                                                    </tr>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <th class="ps-4 py-3 bg-light text-muted small text-uppercase" style="width: 250px;"><?= htmlspecialchars($label) ?></th>
                                                    <td class="ps-4 py-3 fw-medium"><?= htmlspecialchars($value) ?></td>
                                                </tr>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                <div class="tab-pane fade" id="reviews-tab-pane" role="tabpanel" tabindex="0">
                    <div class="text-center py-5">
                        <div class="mb-4"><i class="bi bi-chat-left-text text-muted opacity-25" style="font-size: 5rem;"></i></div>
                        <h4 class="fw-bold text-dark">No reviews yet</h4>
                        <p class="text-muted mb-4">Be the first to share your thoughts on "<?= htmlspecialchars($productName) ?>"</p>
                        <button class="btn btn-primary rounded-pill px-5 fw-bold shadow-sm">Write a Review</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Related Products Section -->
        <?php if (!empty($relatedProducts)):
            // Build a contextual heading: if any related product is from a sibling category, use parent category name
            $relatedInSameCategory = array_filter($relatedProducts, fn($rp) => $rp['category_id'] == $product['category_id'] ?? null);
            $relatedCategoryLabel = !empty($categoryName) ? $categoryName : 'Related';
            ?>
            <div class="related-products best-sellers product-list mt-5 pt-5 border-top">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <h3 class="fw-bold text-dark mb-0">You May Also Like</h3>
                    <a href="<?= $categoryUrl ?>" class="btn btn-outline-primary rounded-pill px-4">More in <?= htmlspecialchars($relatedCategoryLabel) ?></a>
                </div>
                <div class="row gy-4">
                    <?php foreach ($relatedProducts as $relProduct): ?>
                        <div class="col-6 col-md-4 col-lg-3 product-item">
                            <?php
                            $product = $relProduct; // Set $product for product-card component
                            include __DIR__ . '/../components/product-card.php';
                            ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</main>

<style>
    .product-details-page { background: #fdfdfd; }
    .breadcrumb-item + .breadcrumb-item::before { content: "›"; color: #adb5bd; }
    .cursor-pointer { cursor: pointer; }
    .thumb-item { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); border: 2px solid transparent; background: #fff; }
    .thumb-item:hover { transform: scale(1.05); }
    .thumb-item.active { border-color: var(--bs-primary); }
    /* Step-by-step Variant Selector Style */
    .variant-group-card {
        border: 2px solid #f1f5f9;
        border-radius: 16px;
        background-color: #f8fafc;
        transition: all 0.25s ease;
    }
    .variant-group-card:hover {
        border-color: #cbd5e1;
        box-shadow: 0 4px 12px rgba(0,0,0,0.02);
    }
    .variant-option-pill {
        cursor: pointer;
        border: 2px solid #e2e8f0;
        padding: 8px 16px;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
        color: #475569;
        background-color: #fff;
        transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        user-select: none;
    }
    .variant-option-pill:hover:not(.disabled-pill) {
        border-color: var(--bs-primary);
        color: var(--bs-primary);
        transform: translateY(-1px);
    }
    .variant-option-pill.active {
        border-color: var(--bs-primary);
        background-color: #eff6ff;
        color: var(--bs-primary);
        box-shadow: 0 4px 12px rgba(var(--bs-primary-rgb), 0.12);
    }
    .variant-option-pill.disabled-pill {
        opacity: 0.45;
        background-color: #f1f5f9;
        border-color: #e2e8f0;
        color: #cbd5e1;
        cursor: not-allowed;
        text-decoration: line-through;
    }
    .rich-text-content { line-height: 1.8; font-size: 1.1rem; color: #4b5563; }
    .rich-text-content img { max-width: 100%; height: auto; border-radius: 16px; margin: 2rem 0; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
    .rich-text-content h1, .rich-text-content h2, .rich-text-content h3 { color: #111827; margin-top: 2rem; margin-bottom: 1rem; font-weight: 800; }
    .nav-pills .nav-link {
        color: #6b7280;
        background: transparent;
        transition: all 0.3s ease;
        font-size: 0.82rem;
        letter-spacing: 0.08em;
        border-radius: 0;
        border-bottom: 3px solid transparent;
        margin-bottom: -2px;
    }
    .nav-pills .nav-link:hover {
        color: var(--bs-primary);
    }
    .nav-pills .nav-link.active {
        background: transparent;
        color: var(--bs-primary);
        border-bottom-color: var(--bs-primary);
    }
    .nav-pills .nav-link i {
        font-size: 1.1rem;
    }
    .extra-small { font-size: 0.7rem; }
    .letter-spacing-1 { letter-spacing: 0.1em; }

    /* ── Image Zoom ─────────────────────────────── */
    .main-image-wrapper { cursor: zoom-in; }
    .main-image-wrapper.is-zoomed { cursor: crosshair; }
    #main-product-img { transition: transform 0.22s ease; will-change: transform; }
    .zoom-hint-badge {
        position: absolute; bottom: 10px; right: 10px;
        background: rgba(255,255,255,0.88); border: 1px solid #e2e8f0;
        border-radius: 20px; padding: 4px 11px;
        font-size: 0.68rem; color: #6b7280; font-weight: 600;
        pointer-events: none; display: flex; align-items: center; gap: 5px;
        transition: opacity 0.2s; backdrop-filter: blur(4px);
        box-shadow: 0 1px 4px rgba(0,0,0,0.07);
    }
    .main-image-wrapper.is-zoomed .zoom-hint-badge,
    .main-image-wrapper:active .zoom-hint-badge { opacity: 0; }
    @media (max-width: 767px) {
        .main-image-wrapper { cursor: pointer; }
    }
    /* Lightbox */
    #img-lightbox {
        position: fixed; inset: 0; background: rgba(0,0,0,0.92);
        z-index: 99999; display: flex; align-items: center; justify-content: center;
        animation: lb-in 0.18s ease;
    }
    #img-lightbox img { max-width: 95vw; max-height: 90vh; object-fit: contain; border-radius: 8px; }
    #img-lightbox .lb-close {
        position: absolute; top: 16px; right: 16px;
        background: rgba(255,255,255,0.12); border: none; color: #fff;
        border-radius: 50%; width: 44px; height: 44px; font-size: 1.1rem;
        cursor: pointer; display: flex; align-items: center; justify-content: center;
        transition: background 0.15s;
    }
    #img-lightbox .lb-close:hover { background: rgba(255,255,255,0.25); }
    @keyframes lb-in { from { opacity: 0; } to { opacity: 1; } }

    /* Related Products Specific Fixes */
    .related-products .product-card {
        background: #fff;
        border: 1px solid #eee;
        transition: all 0.3s ease;
    }
    .related-products .product-card:hover {
        box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        border-color: transparent;
    }
    .related-products .product-image {
        background: #f8f9fa;
        position: relative;
        padding-top: 100%;
    }
    .related-products .product-image img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const qtyInput = document.getElementById('product-qty');
        const addBtn   = document.querySelector('.btn-main-add');
        const stockStatusText = document.getElementById('stock-status-text');
        const stockDot = document.querySelector('.stock-dot');
        const selectedVariantInput = document.getElementById('selected-variant-slug');
        const mainProductImg = document.getElementById('main-product-img');

        /* ── Quantity Controls ────────────────────────── */
        document.querySelectorAll('.qty-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();

                // If product has variants but none selected
                const variantGroups = document.querySelectorAll('.option-group');
                const variantSlug = selectedVariantInput.value;
                if (variantGroups.length > 0 && !variantSlug) {
                    if (window.showToast) window.showToast('Please select a product variant first.', 'warning');
                    return;
                }

                const delta = parseInt(this.dataset.delta);
                let val = parseInt(qtyInput.value) || 1;
                val += delta;
                const max = parseInt(qtyInput.getAttribute('max')) || 1;

                if (val < 1) val = 1;
                if (val > max) {
                    val = max;
                    if (window.showToast && delta > 0) window.showToast(`Only ${max} units available in stock.`, 'info');
                }
                qtyInput.value = val;
            });
        });

        /* ── Variant Selection ─────────────────────────── */
        // Normalize variants to always have attributes array (backward compatibility)
        variantsData.forEach(v => {
            if (!v.attributes) {
                v.attributes = [{ key: v.key || 'Option', value: v.value || '' }];
            }
        });

        // Extract all unique option keys and their unique values
        const keys = [];
        const valuesByKey = {};
        variantsData.forEach(v => {
            v.attributes.forEach(attr => {
                const k = attr.key;
                const val = attr.value;
                if (!k || !val) return;
                if (!keys.includes(k)) keys.push(k);
                if (!valuesByKey[k]) valuesByKey[k] = [];
                if (!valuesByKey[k].includes(val)) valuesByKey[k].push(val);
            });
        });

        // User's selections state
        let selections = {};

        // Helper to check if a specific key-value option is available based on other selections and stock
        function isOptionAvailable(key, val) {
            return variantsData.some(v => {
                if (parseInt(v.quantity) <= 0) return false;
                
                // Check if this variant matches all selected attributes for OTHER keys
                for (const [selKey, selVal] of Object.entries(selections)) {
                    if (selKey === key) continue;
                    const attr = v.attributes.find(a => a.key === selKey);
                    if (!attr || attr.value !== selVal) return false;
                }
                
                // Check if this variant has this specific key-value option
                const attr = v.attributes.find(a => a.key === key);
                return attr && attr.value === val;
            });
        }

        // Render/re-render variant option group cards
        function updateUI() {
            const groupContainer = document.getElementById('variant-groups-container');
            if (!groupContainer) return;

            let groupsHtml = '';
            keys.forEach(key => {
                const vals = valuesByKey[key] || [];
                groupsHtml += `
                    <div class="card border border-2 rounded-4 mb-3 shadow-sm variant-group-card">
                        <div class="card-body p-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="fw-bold text-dark mb-0" style="font-size: 0.88rem;">${key}</h6>
                                <span class="text-primary small fw-semibold" style="font-size: 0.8rem;">
                                    ${selections[key] ? `Selected: ${selections[key]}` : 'Not Selected'}
                                </span>
                            </div>
                            <div class="d-flex flex-wrap gap-2">
                `;

                vals.forEach(val => {
                    const isSelected = selections[key] === val;
                    const isAvailable = isOptionAvailable(key, val);
                    groupsHtml += `
                        <div class="variant-option-pill ${isSelected ? 'active' : ''} ${!isAvailable ? 'disabled-pill' : ''}"
                             data-key="${key}"
                             data-val="${val}">
                            ${val}
                        </div>
                    `;
                });

                groupsHtml += `
                            </div>
                        </div>
                    </div>
                `;
            });
            groupContainer.innerHTML = groupsHtml;

            // Bind click handlers
            groupContainer.querySelectorAll('.variant-option-pill').forEach(pill => {
                pill.addEventListener('click', function() {
                    if (this.classList.contains('disabled-pill')) return;

                    const k = this.dataset.key;
                    const v = this.dataset.val;

                    if (selections[k] === v) {
                        delete selections[k]; // Toggle off
                    } else {
                        selections[k] = v; // Select
                    }
                    updateUI();
                });
            });

            // Evaluate selection
            const allSelected = keys.every(k => selections[k] !== undefined);

            if (allSelected) {
                const matchedVariant = variantsData.find(v => {
                    return keys.every(k => {
                        const attr = v.attributes.find(a => a.key === k);
                        return attr && attr.value === selections[k];
                    });
                });

                if (matchedVariant) {
                    selectedVariantInput.value = matchedVariant.sub_slug || '';
                    
                    const price = parseFloat(matchedVariant.discount_price || matchedVariant.base_price);
                    const oldPrice = parseFloat(matchedVariant.base_price) > price ? parseFloat(matchedVariant.base_price) : null;

                    const priceContainer = document.querySelector('.product-price');
                    if (priceContainer) {
                        if (oldPrice) {
                            priceContainer.innerHTML = `
                                <div class="d-flex align-items-center gap-3">
                                    <h2 class="current-price text-primary fw-bold mb-0">${price.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</h2>
                                    <span class="text-muted text-decoration-line-through fs-5">${oldPrice.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</span>
                                    <span class="badge bg-danger rounded-pill px-3">Save ${Math.round(((oldPrice - price) / oldPrice) * 100)}%</span>
                                </div>
                            `;
                        } else {
                            priceContainer.innerHTML = `
                                <h2 class="current-price text-primary fw-bold mb-0">${price.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</h2>
                            `;
                        }
                    }

                    const stock = parseInt(matchedVariant.quantity) || 0;
                    if (stock > 0) {
                        stockStatusText.textContent = `In Stock (${stock} units available)`;
                        stockStatusText.className = 'fw-bold text-success';
                        stockDot.className = 'stock-dot bg-success';
                        qtyInput.setAttribute('max', stock);
                        if (parseInt(qtyInput.value) > stock) qtyInput.value = stock;
                        addBtn.disabled = false;
                    } else {
                        stockStatusText.textContent = 'Out of Stock';
                        stockStatusText.className = 'fw-bold text-danger';
                        stockDot.className = 'stock-dot bg-danger';
                        qtyInput.setAttribute('max', 0);
                        qtyInput.value = 1;
                        addBtn.disabled = true;
                    }

                    // Update Image if available
                    const img = matchedVariant.preview_image ? (matchedVariant.preview_image.startsWith('http') ? matchedVariant.preview_image : '<?= BASE_URL ?>' + matchedVariant.preview_image) : '';
                    if (img) {
                        mainProductImg.style.opacity = '0';
                        setTimeout(() => {
                            mainProductImg.src = img;
                            mainProductImg.style.opacity = '1';
                        }, 200);
                        document.querySelectorAll('.thumb-item').forEach(thumb => {
                            const thumbImg = thumb.querySelector('img');
                            if (thumbImg && thumbImg.src === img) {
                                document.querySelectorAll('.thumb-item').forEach(el => el.classList.remove('active'));
                                thumb.classList.add('active');
                            }
                        });
                    }
                } else {
                    // Out of stock / invalid combination
                    selectedVariantInput.value = '';
                    addBtn.disabled = true;
                    stockStatusText.textContent = 'Out of Stock / Unavailable';
                    stockStatusText.className = 'fw-bold text-danger';
                    stockDot.className = 'stock-dot bg-danger';
                }
            } else {
                // Not all selected
                selectedVariantInput.value = '';
                addBtn.disabled = true;

                // Fallback price representation
                const originalPrice = <?= (float)$product['price'] ?>;
                const originalFinalPrice = <?= (float)$product['final_price'] ?>;
                const priceContainer = document.querySelector('.product-price');
                if (priceContainer) {
                    if (originalPrice > originalFinalPrice) {
                        priceContainer.innerHTML = `
                            <div class="d-flex align-items-center gap-3">
                                <h2 class="current-price text-primary fw-bold mb-0">${originalFinalPrice.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</h2>
                                <span class="text-muted text-decoration-line-through fs-5">${originalPrice.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</span>
                                <span class="badge bg-danger rounded-pill px-3">Save ${Math.round(((originalPrice - originalFinalPrice) / originalPrice) * 100)}%</span>
                            </div>
                        `;
                    } else {
                        priceContainer.innerHTML = `
                            <h2 class="current-price text-primary fw-bold mb-0">${originalPrice.toLocaleString(undefined, {minimumFractionDigits: 2})} BDT</h2>
                        `;
                    }
                }

                const missingKeys = keys.filter(k => selections[k] === undefined);
                stockStatusText.textContent = `Please select: ${missingKeys.join(', ')}`;
                stockStatusText.className = 'fw-bold text-warning';
                stockDot.className = 'stock-dot bg-warning';
            }
        }

        function getSelectedPairs() {
            return selections;
        }

        function selectVariantByAttrs(variant) {
            const vAttrs = variant.attributes || [{key: variant.key || '', value: variant.value || ''}];
            vAttrs.forEach(attr => {
                selections[attr.key] = attr.value;
            });
            updateUI();
        }

        // Auto-select keys that have only 1 unique value
        keys.forEach(key => {
            const vals = valuesByKey[key] || [];
            if (vals.length === 1) {
                selections[key] = vals[0];
            }
        });

        // Auto-select first in-stock variant on page load
        (function() {
            const options = document.getElementById('product-options');
            if (!options) return;
            if (variantsData && variantsData.length > 0) {
                // Find first variant that is in stock
                let targetVariant = variantsData.find(v => parseInt(v.quantity) > 0) || variantsData[0];
                if (targetVariant) {
                    const attrs = targetVariant.attributes || [{key: targetVariant.key || '', value: targetVariant.value || ''}];
                    attrs.forEach(attr => {
                        selections[attr.key] = attr.value;
                    });
                }
            }
        })();

        // Initial UI update
        updateUI();

        /* ── Thumbnail Click ──────────────────────────── */
        window.updateMainImage = function(src, thumb) {
            mainProductImg.style.opacity = '0';
            setTimeout(() => {
                mainProductImg.src = src;
                mainProductImg.style.opacity = '1';
            }, 200);
            document.querySelectorAll('.thumb-item').forEach(el => el.classList.remove('active'));
            thumb.classList.add('active');

            // Auto-select the variant whose preview_image matches this thumbnail
            if (variantsData) {
                const match = variantsData.find(v => {
                    const imgPath = v.preview_image ? ('<?= BASE_URL ?>' + v.preview_image) : '';
                    return imgPath === src;
                });
                if (match) selectVariantByAttrs(match);
            }
        };

        /* ── Add to Cart ──────────────────────────────── */
        addBtn.addEventListener('click', async function() {
            const id = this.dataset.id;
            const shopId = this.dataset.shopId || 1;
            const qty = qtyInput.value;
            const variantSlug = selectedVariantInput.value;
            const variantGroups = document.querySelectorAll('.option-group');

            // 1. Check if variant is selected
            if (variantGroups.length > 0 && !variantSlug) {
                if (window.showToast) window.showToast('Please select a product variant first.', 'warning');
                return;
            }

            // 2. Check stock before sending request
            const max = parseInt(qtyInput.getAttribute('max')) || 0;
            if (max <= 0) {
                if (window.showToast) window.showToast('Sorry, this item is out of stock.', 'danger');
                return;
            }

            // Construct detailed item name for toast
            const productName = <?= json_encode($productName) ?>;
            let variantInfo = "";
            const selected = getSelectedPairs();
            const parts = Object.keys(selected).map(k => `${k}: ${selected[k]}`);
            if (parts.length > 0) variantInfo = ` (${parts.join(', ')})`;
            const fullItemName = productName + variantInfo;

            const originalHTML = this.innerHTML;
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Adding...';

            const fd = new FormData();
            fd.append('action', 'add_to_cart');
            fd.append('product_id', id);
            fd.append('shop_id', shopId);
            fd.append('qty', qty);
            if (variantSlug) {
                fd.append('variant_sub_slug', variantSlug);
            }

            try {
                const apiPath = '<?= BASE_URL ?>api/product-controller.php';
                const r = await fetch(apiPath, { method: 'POST', body: fd });
                const res = await r.json();

                if (res.status === 200) {
                    if (window.showToast) window.showToast(`<strong>${fullItemName}</strong> has been added to your cart!`);
                    updateCartBadge(res.data.cart_count);
                    if (typeof refreshCartDrawer === 'function') refreshCartDrawer();
                } else {
                    if (window.showToast) window.showToast(res.message || 'Failed to add product', 'danger');
                }
            } catch (error) {
                console.error('Add to Cart Error:', error);
                if (window.showToast) window.showToast('Connection error', 'danger');
            } finally {
                this.disabled = false;
                this.innerHTML = originalHTML;
            }
        });

        function updateCartBadge(count) {
            const badge = document.getElementById('cart-badge');
            if (badge) {
                badge.textContent = count;
                badge.classList.add('badge-update-animation');
                setTimeout(() => badge.classList.remove('badge-update-animation'), 500);
            }
        }

        /* ── Image Zoom ──────────────────────────────────────── */
        (function() {
            const wrapper = document.querySelector('.main-image-wrapper');
            const img     = document.getElementById('main-product-img');
            if (!wrapper || !img) return;

            const SCALE    = 2.2;
            const isMobile = () => window.innerWidth < 768;

            // Hint badge
            const hint = document.createElement('div');
            hint.className = 'zoom-hint-badge';
            hint.innerHTML = isMobile()
                ? '<i class="bi bi-arrows-fullscreen" style="font-size:.75rem;"></i>Tap to enlarge'
                : '<i class="bi bi-zoom-in" style="font-size:.75rem;"></i>Hover to zoom · Click to enlarge';
            wrapper.appendChild(hint);

            // Update hint text on resize
            window.addEventListener('resize', () => {
                hint.innerHTML = isMobile()
                    ? '<i class="bi bi-arrows-fullscreen" style="font-size:.75rem;"></i>Tap to enlarge'
                    : '<i class="bi bi-zoom-in" style="font-size:.75rem;"></i>Hover to zoom · Click to enlarge';
            });

            // Desktop hover zoom
            wrapper.addEventListener('mousemove', function(e) {
                if (isMobile()) return;
                const r = wrapper.getBoundingClientRect();
                const x = ((e.clientX - r.left) / r.width  * 100).toFixed(2);
                const y = ((e.clientY - r.top)  / r.height * 100).toFixed(2);
                img.style.transition      = 'none';
                img.style.transformOrigin = `${x}% ${y}%`;
                img.style.transform       = `scale(${SCALE})`;
                wrapper.classList.add('is-zoomed');
            });

            wrapper.addEventListener('mouseleave', function() {
                if (isMobile()) return;
                img.style.transition      = 'transform 0.22s ease';
                img.style.transform       = 'scale(1)';
                img.style.transformOrigin = 'center center';
                wrapper.classList.remove('is-zoomed');
            });

            // Click / tap → fullscreen lightbox
            wrapper.addEventListener('click', function() {
                // Reset zoom before opening so the transition looks clean
                img.style.transition      = 'transform 0.15s ease';
                img.style.transform       = 'scale(1)';
                img.style.transformOrigin = 'center center';
                wrapper.classList.remove('is-zoomed');
                openLightbox(img.src);
            });

            function openLightbox(src) {
                const lb  = document.createElement('div');
                lb.id = 'img-lightbox';
                const lbImg = document.createElement('img');
                lbImg.src = src;
                lbImg.alt = '';
                const btn = document.createElement('button');
                btn.className = 'lb-close';
                btn.setAttribute('aria-label', 'Close');
                btn.innerHTML = '<i class="bi bi-x-lg"></i>';
                lb.appendChild(lbImg);
                lb.appendChild(btn);
                document.body.appendChild(lb);

                const close = () => { lb.style.opacity = '0'; setTimeout(() => lb.remove(), 180); };
                btn.addEventListener('click', close);
                lb.addEventListener('click', (e) => { if (e.target === lb) close(); });
                document.addEventListener('keydown', function esc(e) {
                    if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); }
                });
            }
        })();

        /* ── Shared AJAX Add to Cart (for Related Products) ── */
        document.addEventListener('click', async function(e) {
            const ajaxBtn = e.target.closest('.btn-ajax-add');
            if (!ajaxBtn) return;
            if (ajaxBtn.classList.contains('btn-main-add')) return; // Main button handled separately

            e.preventDefault();
            const id = ajaxBtn.dataset.id;
            const productName = ajaxBtn.dataset.name || 'Product';
            const shopId = ajaxBtn.dataset.shopId || 1;
            const variantSubSlug = ajaxBtn.dataset.variantSubSlug || '';
            const originalHTML = ajaxBtn.innerHTML;

            ajaxBtn.disabled = true;
            ajaxBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

            const fd = new FormData();
            fd.append('action', 'add_to_cart');
            fd.append('product_id', id);
            fd.append('shop_id', shopId);
            fd.append('qty', 1);
            if (variantSubSlug) {
                fd.append('variant_sub_slug', variantSubSlug);
            }

            try {
                const apiPath = '<?= BASE_URL ?>api/product-controller.php';
                const r = await fetch(apiPath, { method: 'POST', body: fd });
                const res = await r.json();

                if (res.status === 200) {
                    if (window.showToast) window.showToast(`<strong>${productName}</strong> added to cart!`);
                    updateCartBadge(res.data.cart_count);
                    if (typeof refreshCartDrawer === 'function') refreshCartDrawer();
                } else {
                    if (window.showToast) window.showToast(res.message || 'Failed to add product', 'danger');
                }
            } catch (error) {
                console.error('AJAX Add to Cart Error:', error);
                if (window.showToast) window.showToast('Connection error', 'danger');
            } finally {
                ajaxBtn.disabled = false;
                ajaxBtn.innerHTML = originalHTML;
            }
        });
    });
</script>

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

<?php
$analyticsProduct = [
    'id'           => (int)$product['id'],
    'product_id'   => (int)$product['id'],
    'name'         => $product['product_name'],
    'sku'          => !empty($product['sku']) ? $product['sku'] : ('PROD-' . $product['id']),
    'category'     => $product['category_name'] ?? '',
    'brand'        => $product['brand_name'] ?? '',
    'price'        => (float)$finalPrice,
    'currency'     => getSetting('currency_code', 'BDT'),
    'shop_id'      => (int)($product['shop_id'] ?? 1),
    'shop_name'    => $product['shop_name'] ?? ''
];
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    if (window.CommerceTracker) {
        window.CommerceTracker.productViewed(<?= json_encode($analyticsProduct, JSON_UNESCAPED_UNICODE) ?>);
    }
});
</script>

<!-- Admin-style Toast Implementation (Overrides footer showToast) -->
<div id="admin-toast-container"></div>
<style>
    #admin-toast-container {
        position: fixed; top: 80px; right: 20px; z-index: 99999;
        display: flex; flex-direction: column; gap: 10px;
        pointer-events: none;
    }
    .admin-toast {
        pointer-events: all; background: #fff; border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0,0,0,.13), 0 2px 8px rgba(0,0,0,.07);
        padding: 13px 14px; display: flex; align-items: center; gap: 12px;
        min-width: 280px; max-width: 400px; border-left: 4px solid transparent;
        animation: adm-toast-in .28s cubic-bezier(.34,1.46,.64,1);
        transition: opacity .22s ease, transform .22s ease;
    }
    .admin-toast.hiding { opacity: 0; transform: translateX(16px); }
    .admin-toast.success { border-left-color: #22c55e; }
    .admin-toast.danger  { border-left-color: #ef4444; }
    .admin-toast.warning { border-left-color: #f59e0b; }
    .admin-toast.info    { border-left-color: var(--bs-primary,#0d6efd); }
    .adm-toast-icon {
        width: 34px; height: 34px; border-radius: 50%; flex-shrink: 0;
        display: flex; align-items: center; justify-content: center; font-size: .9rem;
    }
    .admin-toast.success .adm-toast-icon { background: #dcfce7; color: #16a34a; }
    .admin-toast.danger  .adm-toast-icon { background: #fee2e2; color: #dc2626; }
    .admin-toast.warning .adm-toast-icon { background: #fef9c3; color: #d97706; }
    .admin-toast.info    .adm-toast-icon { background: rgba(13,110,253,.1); color: var(--bs-primary,#0d6efd); }
    .adm-toast-msg { flex: 1; font-size: .845rem; font-weight: 500; color: #111827; line-height: 1.45; }
    .adm-toast-close {
        background: none; border: none; color: #9ca3af; cursor: pointer;
        padding: 2px 2px 2px 6px; font-size: .8rem; flex-shrink: 0;
        transition: color .15s; line-height: 1;
    }
    .adm-toast-close:hover { color: #374151; }
    @keyframes adm-toast-in {
        from { opacity: 0; transform: translateX(18px) scale(.95); }
        to   { opacity: 1; transform: translateX(0)    scale(1);   }
    }
</style>
<script>
    (function() {
        const container = document.getElementById('admin-toast-container');
        const ICONS = {
            success: 'bi-check-circle-fill',
            danger:  'bi-x-circle-fill',
            warning: 'bi-exclamation-triangle-fill',
            info:    'bi-info-circle-fill',
        };

        window.showToast = function(message, type = 'success', duration = 4000) {
            if (!container) return;

            const t = document.createElement('div');
            t.className = 'admin-toast ' + type;
            t.innerHTML =
                '<div class="adm-toast-icon"><i class="bi ' + (ICONS[type] || ICONS.info) + '"></i></div>' +
                '<div class="adm-toast-msg">'  + message + '</div>' +
                '<button class="adm-toast-close" aria-label="Dismiss"><i class="bi bi-x-lg"></i></button>';

            const dismiss = () => {
                t.classList.add('hiding');
                setTimeout(() => t.remove(), 240);
            };
            t.querySelector('.adm-toast-close').addEventListener('click', dismiss);
            if (duration > 0) setTimeout(dismiss, duration);
            container.appendChild(t);
        };
    })();
</script>
