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

    <div class="ltn__breadcrumb-area text-left bg-overlay-white-30 bg-image" data-bs-bg="<?php echo e(asset('img/bg/14.jpg')); ?>">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="ltn__breadcrumb-inner">
                        <h1 class="page-title">Shopping Cart</h1>
                        <div class="ltn__breadcrumb-list">
                            <ul>
                                <li><a href="<?php echo e(route('home')); ?>"><span class="ltn__secondary-color"><i
                                                class="fas fa-home"></i></span> Home</a></li>
                                <li>Cart</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="liton__shoping-cart-area mb-120">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">

                    <?php if(session('success')): ?>
                        <div class="alert alert-success"><?php echo e(session('success')); ?></div>
                    <?php endif; ?>

                    <div class="shoping-cart-inner">
                        <?php if(count($cartItems) > 0): ?>
                            <div class="shoping-cart-table table-responsive">
                                <table class="table" id="cart-table">
                                    <thead>
                                        <tr>
                                            <th class="cart-product-remove">Remove</th>
                                            <th class="cart-product-image">Image</th>
                                            <th class="cart-product-info">Product</th>
                                            <th class="cart-product-price">Price</th>
                                            <th class="cart-product-quantity">Quantity</th>
                                            <th class="cart-product-subtotal">Subtotal</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $__currentLoopData = $cartItems; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <tr data-cart-item-id="<?php echo e($item->id); ?>"
                                                data-price="<?php echo e($item->product->is_on_sale && $item->product->discount_price ? $item->product->discount_price : $item->product->price); ?>">
                                                <td class="cart-product-remove">
                                                    <a href="#" class="remove-cart-item"
                                                        data-item-id="<?php echo e($item->id); ?>">
                                                        <i class="fas fa-times"></i>
                                                    </a>
                                                </td>
                                                <td class="cart-product-image">
                                                    <a href="<?php echo e(route('product.show', $item->product->slug)); ?>">
                                                        <?php if($item->product->images->count() > 0): ?>
                                                            <img src="<?php echo e(asset('storage/' . $item->product->images->first()->image)); ?>"
                                                                alt="<?php echo e($item->product->name); ?>" style="width:80px;">
                                                        <?php else: ?>
                                                            <img src="<?php echo e(asset('img/product/default.png')); ?>"
                                                                alt="<?php echo e($item->product->name); ?>" style="width:80px;">
                                                        <?php endif; ?>
                                                    </a>
                                                </td>
                                                <td class="cart-product-info">
                                                    <h4><a
                                                            href="<?php echo e(route('product.show', $item->product->slug)); ?>"><?php echo e($item->product->name); ?></a>
                                                    </h4>
                                                </td>
                                                <td class="cart-product-price">
                                                    <?php
                                                        $price =
                                                            $item->product->is_on_sale && $item->product->discount_price
                                                                ? $item->product->discount_price
                                                                : $item->product->price;
                                                    ?>
                                                    $<?php echo e(number_format($price, 2)); ?>

                                                </td>
                                                <td class="cart-product-quantity">
                                                    <div class="cart-plus-minus">
                                                        <input type="text" value="<?php echo e($item->quantity); ?>"
                                                            name="qtybutton" class="cart-plus-minus-box cart-qty-input"
                                                            data-item-id="<?php echo e($item->id); ?>" min="1">
                                                    </div>
                                                </td>
                                                <td class="cart-product-subtotal item-subtotal">
                                                    $<?php echo e(number_format($price * $item->quantity, 2)); ?>

                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </tbody>
                                </table>
                            </div>

                            <div class="shoping-cart-total mt-50">
                                <h4>Cart Totals</h4>
                                <table class="table">
                                    <tbody>
                                        <tr>
                                            <td>Cart Subtotal</td>
                                            <td id="cart-subtotal">$<?php echo e(number_format($subtotal, 2)); ?></td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <strong>Shipping</strong>
                                                <div class="mt-2">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="shipping_type"
                                                            id="shipping_discrete" value="30" checked>
                                                        <label class="form-check-label" for="shipping_discrete">
                                                            Discrete Shipping — <strong>$30.00</strong>
                                                            <small class="d-block text-muted">Plain packaging, no
                                                                labels</small>
                                                        </label>
                                                    </div>
                                                    <div class="form-check mt-2">
                                                        <input class="form-check-input" type="radio" name="shipping_type"
                                                            id="shipping_non_discrete" value="60">
                                                        <label class="form-check-label" for="shipping_non_discrete">
                                                            Non-Discrete Shipping — <strong>$60.00</strong>
                                                            <small class="d-block text-muted">Standard packaging</small>
                                                        </label>
                                                    </div>
                                                </div>
                                            </td>
                                            <td id="shipping-cost">$30.00</td>
                                        </tr>
                                        <tr>
                                            <td>VAT</td>
                                            <td>$0.00</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Order Total</strong></td>
                                            <td><strong id="cart-total">$<?php echo e(number_format($subtotal + 30, 2)); ?></strong>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <div class="btn-wrapper text-right text-end">
                                    <a href="<?php echo e(route('checkout')); ?>" class="theme-btn-1 btn btn-effect-1">
                                        Proceed to Checkout
                                    </a>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="fas fa-shopping-cart fa-4x mb-3" style="color:#ddd;"></i>
                                <h3>Your cart is empty</h3>
                                <a href="<?php echo e(route('shop')); ?>" class="theme-btn-1 btn btn-effect-1 mt-3">Continue
                                    Shopping</a>
                            </div>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
        </div>
    </div>

   <?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const csrf    = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    let SHIPPING  = 30.00; // default: discrete

    // ── Shipping selector ────────────────────────────────────────────────────
    document.querySelectorAll('input[name="shipping_type"]').forEach(radio => {
        radio.addEventListener('change', function () {
            SHIPPING = parseFloat(this.value);
            document.getElementById('shipping-cost').textContent = '$' + SHIPPING.toFixed(2);
            recalcTotals();

            // Save choice to session via AJAX
            fetch('/cart/shipping', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ shipping_type: this.id, shipping_cost: SHIPPING })
            }).catch(err => console.error('Shipping update error:', err));
        });
    });

    // ── Recalculate totals ───────────────────────────────────────────────────
    function recalcTotals() {
        let subtotal = 0;
        document.querySelectorAll('#cart-table tbody tr').forEach(row => {
            const price   = parseFloat(row.dataset.price) || 0;
            const input   = row.querySelector('.cart-qty-input');
            const qty     = parseInt(input ? input.value : 1) || 1;
            const sub     = price * qty;
            const subCell = row.querySelector('.item-subtotal');
            if (subCell) subCell.textContent = '$' + sub.toFixed(2);
            subtotal += sub;
        });
        const subtotalEl = document.getElementById('cart-subtotal');
        const totalEl    = document.getElementById('cart-total');
        if (subtotalEl) subtotalEl.textContent = '$' + subtotal.toFixed(2);
        if (totalEl)    totalEl.textContent    = '$' + (subtotal + SHIPPING).toFixed(2);
    }

    // ── AJAX update quantity ─────────────────────────────────────────────────
    let debounceTimers = {};

    function updateCartItem(itemId, qty) {
        clearTimeout(debounceTimers[itemId]);
        debounceTimers[itemId] = setTimeout(() => {
            fetch('/cart/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ item_id: itemId, quantity: qty })
            })
            .then(r => r.json())
            .then(data => {
                if (data.cart_count !== undefined) {
                    document.querySelectorAll('.mini-cart-icon sup').forEach(el => {
                        el.textContent = data.cart_count;
                    });
                }
            })
            .catch(err => console.error('Update error:', err));
        }, 500);
    }

    // ── Bind +/- theme buttons ───────────────────────────────────────────────
    function bindPlusMinusButtons() {
        document.querySelectorAll('.cart-plus-minus').forEach(wrapper => {
            const input  = wrapper.querySelector('.cart-qty-input');
            if (!input) return;
            const itemId = input.dataset.itemId;
            const minus  = wrapper.querySelector('.dec.qtybutton');
            const plus   = wrapper.querySelector('.inc.qtybutton');

            if (minus) {
                minus.addEventListener('click', () => setTimeout(() => {
                    let qty = Math.max(1, parseInt(input.value) || 1);
                    input.value = qty;
                    recalcTotals();
                    updateCartItem(itemId, qty);
                }, 50));
            }
            if (plus) {
                plus.addEventListener('click', () => setTimeout(() => {
                    let qty = parseInt(input.value) || 1;
                    recalcTotals();
                    updateCartItem(itemId, qty);
                }, 50));
            }

            input.addEventListener('change', function () {
                let qty = Math.max(1, parseInt(this.value) || 1);
                this.value = qty;
                recalcTotals();
                updateCartItem(itemId, qty);
            });

            input.addEventListener('input', function () {
                recalcTotals();
                updateCartItem(itemId, parseInt(this.value) || 1);
            });
        });
    }

    setTimeout(bindPlusMinusButtons, 300);

    // ── Poll for theme-driven value changes ──────────────────────────────────
    let lastValues = {};
    document.querySelectorAll('.cart-qty-input').forEach(input => {
        lastValues[input.dataset.itemId] = input.value;
    });

    setInterval(() => {
        document.querySelectorAll('.cart-qty-input').forEach(input => {
            const itemId = input.dataset.itemId;
            if (input.value !== lastValues[itemId]) {
                lastValues[itemId] = input.value;
                recalcTotals();
                updateCartItem(itemId, parseInt(input.value) || 1);
            }
        });
    }, 200);

    // ── Remove item ──────────────────────────────────────────────────────────
    document.querySelectorAll('.remove-cart-item').forEach(btn => {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const itemId = this.dataset.itemId;
            const row    = this.closest('tr');

            fetch('/cart/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ item_id: itemId })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    row.remove();
                    recalcTotals();
                    document.querySelectorAll('.mini-cart-icon sup').forEach(el => {
                        el.textContent = data.cart_count;
                    });
                    if (!document.querySelectorAll('#cart-table tbody tr').length) location.reload();
                }
            })
            .catch(err => console.error('Remove error:', err));
        });
    });

    // ── Initial calc ─────────────────────────────────────────────────────────
    recalcTotals();
});
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Users/ozil/notrace/resources/views/cart.blade.php ENDPATH**/ ?>