<?php $__env->startSection('title', $product->name); ?>

<?php $__env->startSection('content'); ?>

<div class="hhd-breadcrumb">
    <div class="container small">
        <a href="<?php echo e(route('home')); ?>" class="text-muted-soft">Home</a> /
        <a href="<?php echo e(route('shop.index')); ?>" class="text-muted-soft">Shop</a> /
        <a href="<?php echo e(route('shop.index', ['category' => $product->category->slug])); ?>" class="text-muted-soft"><?php echo e($product->category->name); ?></a> /
        <span class="text-charcoal"><?php echo e($product->name); ?></span>
    </div>
</div>

<div class="container py-5">
    <div class="row g-5">
        <div class="col-lg-6">
            <?php
                $defaultImage = $product->image
                    ? asset('storage/'.$product->image)
                    : 'https://placehold.co/600x600/f0e8dc/2b2622?text=Home+Heaven+Decors';

                $thumbs = collect();
                if ($product->image) {
                    $thumbs->push(asset('storage/'.$product->image));
                }
                foreach ($product->images as $img) {
                    $thumbs->push(asset('storage/'.$img->image));
                }
                if ($product->has_variants) {
                    foreach ($product->variants as $variant) {
                        foreach ($variant->images as $vimg) {
                            $thumbs->push(asset('storage/'.$vimg->image));
                        }
                    }
                }
                $thumbs = $thumbs->unique()->values();
            ?>
            <div class="product-image-wrap rounded mb-3" style="aspect-ratio:1/1;">
                <img id="mainImage" src="<?php echo e($defaultImage); ?>" data-default="<?php echo e($defaultImage); ?>" class="w-100 h-100" style="object-fit:cover;" alt="<?php echo e($product->name); ?>">
            </div>
            <?php if($thumbs->count() > 1): ?>
                <div class="d-flex gap-2 flex-wrap">
                    <?php $__currentLoopData = $thumbs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $thumb): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <img src="<?php echo e($thumb); ?>" class="rounded border" style="width:70px;height:70px;object-fit:cover;cursor:pointer;" onclick="document.getElementById('mainImage').src=this.src">
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-lg-6">
            <div class="product-category mb-2"><?php echo e($product->category->name); ?></div>
            <h1 class="font-serif mb-3" style="font-size:1.9rem;"><?php echo e($product->name); ?></h1>

            <div class="mb-3">
                <span id="pdpComparePrice" class="price-compare fs-5 <?php echo e($product->compare_price && $product->compare_price > $product->price ? '' : 'd-none'); ?>">Rs. <?php echo e(number_format($product->compare_price ?? 0)); ?></span>
                <span id="pdpPrice" class="fs-3 fw-semibold text-terracotta">Rs. <?php echo e(number_format($product->price)); ?></span>
            </div>

            <?php if($product->short_description): ?>
                <p class="text-muted-soft"><?php echo e($product->short_description); ?></p>
            <?php endif; ?>

            <?php if($product->has_variants): ?>
                <?php $matrix = $product->variantMatrix(); ?>

                <div id="pdpVariants" class="mb-3">
                    <?php $__currentLoopData = $matrix['attributes']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attr): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="mb-3 variant-attr" data-attr="<?php echo e($attr['name']); ?>">
                            <div class="small text-uppercase text-muted-soft mb-2"><?php echo e($attr['name']); ?>: <span class="fw-semibold text-charcoal js-chosen">—</span></div>
                            <div class="d-flex flex-wrap gap-2">
                                <?php $__currentLoopData = $attr['values']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <button type="button" class="variant-chip" data-attr="<?php echo e($attr['name']); ?>" data-value="<?php echo e($value); ?>"><?php echo e($value); ?></button>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>

                <div class="mb-4">
                    <span id="pdpStockBadge" class="badge bg-secondary-subtle text-muted border">Select options</span>
                </div>

                <form id="pdpAddForm" action="<?php echo e(route('cart.add', $product)); ?>" method="POST" class="d-flex align-items-center gap-3 mb-4">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="product_variant_id" id="pdpVariantId" value="">
                    <input type="number" name="quantity" value="1" min="1" max="1" class="form-control qty-input" id="pdpQty" disabled>
                    <button type="submit" class="btn btn-terracotta px-4" id="pdpAddBtn" disabled><i class="bi bi-bag-plus me-2"></i>Add to Cart</button>
                </form>

                <?php $__env->startPush('scripts'); ?>
                <script>
                (function () {
                    const matrix = <?php echo json_encode($matrix, 15, 512) ?>;
                    const attrNames = matrix.attributes.map(a => a.name);
                    const selected = {};
                    const chips = document.querySelectorAll('#pdpVariants .variant-chip');
                    const priceEl = document.getElementById('pdpPrice');
                    const compareEl = document.getElementById('pdpComparePrice');
                    const stockBadge = document.getElementById('pdpStockBadge');
                    const variantIdInput = document.getElementById('pdpVariantId');
                    const qty = document.getElementById('pdpQty');
                    const addBtn = document.getElementById('pdpAddBtn');
                    const mainImage = document.getElementById('mainImage');
                    const defaultImage = mainImage ? mainImage.getAttribute('data-default') : null;
                    const fmt = n => 'Rs. ' + Number(n).toLocaleString('en-PK');

                    // Best image for the current (possibly partial) selection:
                    // the chosen combo's image, else any variant matching the
                    // partial selection that has one, else the product default.
                    function pickImage(combo) {
                        if (combo && combo.image) return combo.image;

                        const keys = Object.keys(selected);
                        if (keys.length) {
                            const partial = matrix.combinations.find(c =>
                                c.image && keys.every(n => String(c.options[n]) === String(selected[n]))
                            );
                            if (partial) return partial.image;
                        }

                        return defaultImage;
                    }

                    function matchCombo(sel) {
                        return matrix.combinations.find(c =>
                            attrNames.every(n => String(c.options[n]) === String(sel[n]))
                        );
                    }

                    // Is there ANY in-stock combo consistent with the partial selection + this candidate?
                    function optionPossible(attr, value) {
                        const probe = Object.assign({}, selected, { [attr]: value });
                        return matrix.combinations.some(c =>
                            c.in_stock &&
                            Object.keys(probe).every(n => String(c.options[n]) === String(probe[n]))
                        );
                    }

                    function refresh() {
                        chips.forEach(chip => {
                            const a = chip.dataset.attr, v = chip.dataset.value;
                            chip.classList.toggle('is-selected', selected[a] === v);
                            const disabled = !optionPossible(a, v);
                            chip.classList.toggle('is-disabled', disabled);
                            chip.disabled = disabled;
                        });
                        matrix.attributes.forEach(a => {
                            const holder = document.querySelector('.variant-attr[data-attr="' + a.name + '"] .js-chosen');
                            if (holder) holder.textContent = selected[a.name] || '—';
                        });

                        const complete = attrNames.every(n => selected[n]);
                        const combo = complete ? matchCombo(selected) : null;

                        // Swap the main product image for the current selection.
                        if (mainImage) {
                            const nextSrc = pickImage(combo);
                            if (nextSrc && mainImage.src !== nextSrc) mainImage.src = nextSrc;
                        }

                        if (combo) {
                            priceEl.textContent = fmt(combo.price);
                            if (combo.compare_price && combo.compare_price > combo.price) {
                                compareEl.textContent = fmt(combo.compare_price);
                                compareEl.classList.remove('d-none');
                            } else {
                                compareEl.classList.add('d-none');
                            }

                            if (combo.in_stock) {
                                stockBadge.className = 'badge bg-success-subtle text-success border border-success-subtle';
                                stockBadge.innerHTML = '<i class="bi bi-check-circle me-1"></i>In Stock (' + combo.stock + ' available)';
                                variantIdInput.value = combo.id;
                                qty.disabled = false;
                                qty.max = combo.stock;
                                if (Number(qty.value) > combo.stock) qty.value = combo.stock;
                                if (Number(qty.value) < 1) qty.value = 1;
                                addBtn.disabled = false;
                            } else {
                                stockBadge.className = 'badge bg-danger-subtle text-danger border border-danger-subtle';
                                stockBadge.textContent = 'Out of Stock';
                                variantIdInput.value = '';
                                qty.disabled = true;
                                addBtn.disabled = true;
                            }
                        } else {
                            variantIdInput.value = '';
                            qty.disabled = true;
                            addBtn.disabled = true;
                            stockBadge.className = 'badge bg-secondary-subtle text-muted border';
                            stockBadge.textContent = complete ? 'This combination is unavailable' : 'Select options';
                        }
                    }

                    chips.forEach(chip => chip.addEventListener('click', function () {
                        const a = chip.dataset.attr, v = chip.dataset.value;
                        selected[a] = (selected[a] === v) ? undefined : v;
                        if (selected[a] === undefined) delete selected[a];
                        refresh();
                    }));

                    document.getElementById('pdpAddForm').addEventListener('submit', function (e) {
                        if (!variantIdInput.value) { e.preventDefault(); }
                    });

                    refresh();
                })();
                </script>
                <?php $__env->stopPush(); ?>
            <?php else: ?>
                <div class="mb-4">
                    <?php if($product->isInStock()): ?>
                        <span class="badge bg-success-subtle text-success border border-success-subtle"><i class="bi bi-check-circle me-1"></i>In Stock (<?php echo e($product->stock_quantity); ?> available)</span>
                    <?php else: ?>
                        <span class="badge bg-danger-subtle text-danger border border-danger-subtle">Out of Stock</span>
                    <?php endif; ?>
                </div>

                <?php if($product->isInStock()): ?>
                    <form action="<?php echo e(route('cart.add', $product)); ?>" method="POST" class="d-flex align-items-center gap-3 mb-4">
                        <?php echo csrf_field(); ?>
                        <input type="number" name="quantity" value="1" min="1" max="<?php echo e($product->stock_quantity); ?>" class="form-control qty-input">
                        <button type="submit" class="btn btn-terracotta px-4"><i class="bi bi-bag-plus me-2"></i>Add to Cart</button>
                    </form>
                <?php endif; ?>
            <?php endif; ?>

            <hr class="my-4">

            <div class="d-flex gap-4 small text-muted-soft mb-4">
                <div><i class="bi bi-truck me-1"></i> Nationwide Delivery</div>
                <div><i class="bi bi-cash-coin me-1"></i> Cash on Delivery</div>
            </div>

            <?php if($product->description): ?>
                <h5 class="font-serif">Description</h5>
                <div class="text-muted-soft"><?php echo nl2br(e($product->description)); ?></div>
            <?php endif; ?>
        </div>
    </div>

    <?php if($related->count()): ?>
        <div class="mt-5 pt-4">
            <div class="section-title text-start">
                <h2 style="font-size:1.6rem;">You May Also Like</h2>
                <div class="section-divider" style="margin-left:0;"></div>
            </div>
            <div class="row g-4">
                <?php $__currentLoopData = $related; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $rp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="col-6 col-md-3">
                        <?php echo $__env->make('partials.product-card', ['product' => $rp], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\homeheavendecor\resources\views/shop/show.blade.php ENDPATH**/ ?>