

<?php $__env->startSection('title', 'Shopping Cart - ' . \App\Models\Setting::get('site_name', 'KiyoKart')); ?>

<?php $__env->startSection('styles'); ?>
<style>
    /* Cart thumbnails: 50x50 (override homepage.css) */
    .cart-item-thumb-wrap {
        width: 50px;
        height: 50px;
        min-width: 50px;
        min-height: 50px;
        flex-shrink: 0;
        overflow: hidden;
        border-radius: 8px;
        border: 2px solid var(--border-color, #e5e7eb);
    }
    .cart-item-thumb-wrap picture,
    .cart-item-thumb-wrap .cart-item-image {
        width: 50px !important;
        height: 50px !important;
        max-width: 50px !important;
        max-height: 50px !important;
        display: block;
        overflow: hidden;
    }
    .cart-item-thumb-wrap picture img,
    .cart-item-thumb-wrap img.cart-item-image {
        width: 100% !important;
        height: 100% !important;
        max-width: 50px !important;
        max-height: 50px !important;
        object-fit: cover;
        display: block;
    }
    .cart-item-thumb-wrap .cart-item-image-placeholder {
        width: 50px !important;
        height: 50px !important;
        min-width: 50px !important;
        min-height: 50px !important;
    }

    .cart-item-out-of-stock {
        opacity: 0.7;
        background-color: #fff5f5;
        border-left: 3px solid #dc3545;
    }
    
    .cart-item-out-of-stock .cart-item-name {
        color: #6c757d;
    }
    
    .cart-item-stock .alert {
        margin-bottom: 0;
        padding: 0.4rem 0.75rem;
        border-radius: 4px;
    }
    
    .cart-item-stock .alert-danger {
        background-color: #f8d7da;
        border-color: #f5c6cb;
        color: #721c24;
    }
    
    .cart-item-stock .alert-warning {
        background-color: #fff3cd;
        border-color: #ffeaa7;
        color: #856404;
    }
    
    .btn-checkout.disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    .btn-checkout.disabled:hover {
        opacity: 0.6;
    }

    .coupon-card-disabled {
        opacity: 0.6;
        background-color: #f5f5f5;
        cursor: not-allowed;
    }

    .coupon-card-disabled:hover {
        transform: none;
        box-shadow: none;
        border-color: #e0e0e0;
    }

    .btn-coupon-disabled {
        background-color: #6c757d !important;
        color: #fff !important;
        cursor: not-allowed !important;
        opacity: 0.7;
    }

    .btn-coupon-disabled:hover {
        background-color: #6c757d !important;
    }
</style>
<script>
function validateStockBeforeCheckout(event) {
    event.preventDefault();
    
    // Get stock issues from the alert message
    const alertDiv = document.querySelector('.alert-danger');
    if (alertDiv) {
        const issueList = alertDiv.querySelector('ul');
        let message = 'Cannot proceed to checkout due to stock issues:\n\n';
        
        if (issueList) {
            const issues = issueList.querySelectorAll('li');
            issues.forEach((issue, index) => {
                message += (index + 1) + '. ' + issue.textContent.trim() + '\n';
            });
        }
        
        message += '\nPlease update quantities or remove items before checkout.';
        alert(message);
    } else {
        alert('Some items in your cart have stock issues. Please review and update your cart before proceeding to checkout.');
    }
    
    return false;
}

// Apply loading state to checkout button
document.addEventListener('DOMContentLoaded', () => {
    const checkoutBtn = document.getElementById('checkoutBtn');
    if (!checkoutBtn) return;

    checkoutBtn.addEventListener('click', function (e) {
        // Allow stock validation handler to run when disabled via issues
        if (this.classList.contains('disabled')) {
            return;
        }

        e.preventDefault();

        if (!this.dataset.originalContent) {
            this.dataset.originalContent = this.innerHTML;
        }

        this.classList.add('disabled');
        this.innerHTML = `
            <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
            Processing...
        `;

        // Navigate after showing loader
        window.location.href = this.href;
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="tw-migrated">
<div style="background: #F9FAFB;">
<div class="container cart-page-container">
    <h1 class="cart-page-title">
        <i class="bi bi-cart3"></i>
        Shopping Cart
    </h1>

    <?php if($cart->items->count()): ?>
        <div class="row">
            <div class="col-md-7 col-lg-8">
                <div class="cart-items-card">
                    <?php $__currentLoopData = $cart->items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php
                            $product = $item->product;
                            $productName = $product->name ?? 'Product unavailable';
                            $productHasImage = $product && ($product->image_path || $product->image);
                            $productUrl = null;

                            if ($product) {
                                $parentSlug = optional($product->parent)->slug;

                                if ($product->parent_id && $parentSlug) {
                                    $productUrl = route('product.show', ['slug' => $parentSlug]) . '?variant=' . $product->id;
                                } elseif ($product->slug) {
                                    $productUrl = route('product.show', $product->slug);
                                }
                            }

                            // Get stock information based on product type (online = sum of Fulfills-online)
                            if ($item->product_variant_id && $item->productVariant) {
                                $availableStock = $item->productVariant->onlineAvailableStock();
                                $isOutOfStock = $availableStock <= 0;
                                $isLowStock = $availableStock < $item->qty;
                                $variantName = $item->productVariant->variation_name;
                            } elseif ($product) {
                                $availableStock = $product->onlineAvailableStock();
                                $isOutOfStock = $availableStock <= 0;
                                $isLowStock = $availableStock < $item->qty;
                                $variantName = null;
                            } else {
                                $availableStock = 0;
                                $isOutOfStock = $availableStock <= 0;
                                $isLowStock = $availableStock < $item->qty;
                                $variantName = null;
                            }
                        ?>
                        <div class="cart-item-row gap-2 <?php echo e($isOutOfStock ? 'cart-item-out-of-stock' : ''); ?>">
                            <div class="cart-item-thumb-wrap">
                                <?php if($productHasImage): ?>
                                    <?php if (isset($component)) { $__componentOriginala58dde406db9207f2e2c58e1c4a3d690 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.product-image','data' => ['product' => $product,'context' => 'small','class' => 'cart-item-image','alt' => ''.e($productName).'']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('product-image'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['product' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($product),'context' => 'small','class' => 'cart-item-image','alt' => ''.e($productName).'']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $attributes = $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
<?php if (isset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $component = $__componentOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
                                <?php else: ?>
                                    <div class="cart-item-image-placeholder">
                                        <i class="bi bi-image"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="cart-item-details">
                                <?php if($productUrl): ?>
                                  <?php 
                                    $trimproductName = $productName . ($variantName ? ' - ' . $variantName : '');
                                  ?>
                                    <a href="<?php echo e($productUrl); ?>" class="cart-item-name" title="<?php echo e($productName); ?><?php echo e($variantName ? ' - ' . $variantName : ''); ?>">
                                        <?php echo e($trimproductName); ?>

                                    </a>
                                <?php else: ?>
                                    <span class="cart-item-name">
                                        <?php echo e($productName); ?>

                                        <small class="text-danger d-block" style="font-size: 0.85em; font-weight: normal;">
                                            This product is no longer available.
                                        </small>
                                    </span>
                                <?php endif; ?>
                                <div class="cart-item-price">
                                    ₹<?php echo e(number_format($item->price_at_add, 2)); ?>

                                </div>
                                
                                <!-- Stock Status -->
                                <div class="cart-item-stock mt-2">
                                    <?php if($isOutOfStock): ?>
                                        <div class="alert alert-danger mb-0 py-1 px-2" style="font-size: 0.85em;">
                                            <i class="bi bi-exclamation-triangle-fill"></i>
                                            <strong>Out of Stock</strong> - This item is currently unavailable
                                        </div>
                                    <?php elseif($isLowStock): ?>
                                        <div class="alert alert-warning mb-0 py-1 px-2" style="font-size: 0.85em;">
                                            <i class="bi bi-exclamation-circle-fill"></i>
                                            <strong>Low Stock</strong> - Only <?php echo e($availableStock); ?> available (You have <?php echo e($item->qty); ?> in cart)
                                        </div>
                                    <?php else: ?>
                                        <div class="text-success" style="font-size: 0.85em;">
                                            <i class="bi bi-check-circle-fill"></i>
                                            <strong>In Stock</strong> - <?php echo e($availableStock); ?> available
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="cart-item-qty d-inline-flex align-items-center gap-2">
                                <form action="<?php echo e(route('cart.update', $item->product_id)); ?>" method="POST" class="d-inline-flex align-items-center gap-2 cart-qty-form" data-min="1" data-max="<?php echo e($availableStock); ?>">
                                    <?php echo csrf_field(); ?>
                                    <?php echo method_field('PUT'); ?>
                                    <input type="hidden" name="qty" value="<?php echo e($item->qty); ?>">
                                    <button type="button" 
                                            class="cart-qty-btn cart-qty-minus <?php echo e($isOutOfStock ? 'btn-secondary' : ''); ?>"
                                            aria-label="Decrease quantity"
                                            <?php echo e($isOutOfStock || $item->qty <= 1 ? 'disabled' : ''); ?>>
                                        <i class="bi bi-dash"></i>
                                    </button>
                                    <span class="cart-qty-value" aria-live="polite"><?php echo e($item->qty); ?></span>
                                    <button type="button" 
                                            class="cart-qty-btn cart-qty-plus <?php echo e($isOutOfStock ? 'btn-secondary' : ''); ?>"
                                            aria-label="Increase quantity"
                                            <?php echo e($isOutOfStock || $item->qty >= $availableStock ? 'disabled' : ''); ?>>
                                        <i class="bi bi-plus"></i>
                                    </button>
                                    <div class="cart-item-total">
                                        ₹<?php echo e(number_format($item->line_total, 2)); ?>

                                    </div>
                                </form>
                                <form action="<?php echo e(route('cart.destroy', $item->product_id)); ?>" method="POST" class="d-inline-flex">
                                    <?php echo csrf_field(); ?>
                                    <?php echo method_field('DELETE'); ?>
                                    <button type="submit" class="btn-cart-delete" onclick="return confirm('Are you sure you want to remove this item?')">
                                        <i class="bi bi-x"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>

	    <div class="col-md-5 col-lg-4">
            <div class="cart-summary-card">
                <div class="cart-summary-header">
                    <h5>
                        <i class="bi bi-receipt"></i>
                        Cart Summary
                    </h5>
                </div>         
                <div class="cart-summary-body">
                    <div class="coupon-section">
                        <?php if($cart->coupon): ?>
                            <h6 class="mb-2">
                                <i class="bi bi-ticket-perforated"></i>
                                Applied Coupon
                            </h6>
                            <div class="coupon-success-alert mb-3">
                                <span>
                                    <i class="bi bi-check-circle-fill"></i>
                                    Coupon "<?php echo e($cart->coupon->code); ?>" applied!
                                </span>
                                <form action="<?php echo e(route('cart.remove-coupon')); ?>" method="POST" class="d-inline">
                                    <?php echo csrf_field(); ?>
                                    <button type="submit" class="btn-coupon-remove" title="Remove"><i class="bi bi-trash"></i></button>
                                </form>
                            </div>
                        <?php else: ?>
                            <h6 class="mb-2">
                                <i class="bi bi-ticket-perforated"></i>
                                Apply Coupon
                            </h6>
                            <form action="<?php echo e(route('cart.apply-coupon')); ?>" method="POST" id="coupon-form" class="mb-3">
                                <?php echo csrf_field(); ?>
                                <div class="coupon-input-group">
                                    <input type="text" 
                                           name="code" 
                                           class="coupon-input form-control" 
                                           placeholder="Enter coupon code" 
                                           required>
                                    <button type="submit" class="btn-coupon-validate">Validate</button>
                                </div>
                            </form>
                        <?php endif; ?>

                        <?php if(isset($availableCoupons) && count($availableCoupons) > 0): ?>
                            <!-- COUPONS HEADER (CLICKABLE) -->
                            <div class="coupons-header d-flex justify-content-between align-items-center border p-2"
                                onclick="toggleCoupons()" style="cursor:pointer;">
                                <div>
                                    <strong>Coupons</strong><br>
                                    <small class="text-muted">Apply now and save extra!</small>
                                </div>
                                <i class="bi bi-chevron-right" id="couponArrow"></i>
                            </div>
                            <!-- COUPONS LIST (HIDDEN INITIALLY) -->
                            <div class="available-coupons-section mt-3" id="couponList" style="display:none;">
                                <h6 class="mb-2" style="font-size: 0.9rem; color: #6c757d;">
                                    <i class="bi bi-tags"></i>
                                    Available Coupons
                                </h6>
                                <div class="available-coupons-list">
                                    <?php $__currentLoopData = $availableCoupons; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $coupon): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <?php if(!$cart->coupon || $cart->coupon->id != $coupon['id']): ?>
                                            <div class="coupon-card <?php echo e(!$coupon['is_eligible'] ? 'coupon-card-disabled' : ''); ?>" 
                                                 data-coupon-code="<?php echo e($coupon['code']); ?>"
                                                 data-is-eligible="<?php echo e($coupon['is_eligible'] ? 'true' : 'false'); ?>">
                                                <div class="coupon-card-body p-0">
                                                    <div class="coupon-card-details p-3 d-flex justify-content-between align-items-center">
                                                        <div class="coupon-card-first">
                                                            <span class="coupon-discount <?php echo e(!$coupon['is_eligible'] ? 'text-muted' : ''); ?>" style="<?php echo e($coupon['is_eligible'] ? 'color:var(--hover-color)' : ''); ?>">
                                                                <?php if($coupon['type'] === 'percentage'): ?>
                                                                    Flat <?php echo e($coupon['value']); ?>% OFF
                                                                <?php else: ?>
                                                                    Flat ₹<?php echo e(number_format($coupon['value'], 2)); ?> OFF
                                                                <?php endif; ?>
                                                            </span>
                                                            <!-- SECOND LINE -->
                                                            <div class="coupon-savings">
                                                                <strong class="<?php echo e(!$coupon['is_eligible'] ? 'text-muted' : ''); ?>">Save ₹<?php echo e(number_format($coupon['discount_preview'], 2)); ?></strong>
                                                                <?php if($coupon['min_cart_value']): ?>
                                                                    <small class="text-muted d-block">
                                                                        Min. cart value: ₹<?php echo e(number_format($coupon['min_cart_value'], 2)); ?>

                                                                    </small>
                                                                <?php endif; ?>
                                                                <?php if(!$coupon['is_eligible'] && $coupon['eligibility_reason']): ?>
                                                                    <small class="text-danger d-block mt-1">
                                                                        <i class="bi bi-exclamation-circle"></i> <?php echo e($coupon['eligibility_reason']); ?>

                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>


                                                            <!-- COUPON CODE BADGE -->
                                                            <span class="coupon-code <?php echo e(!$coupon['is_eligible'] ? 'text-muted' : ''); ?>" style="<?php echo e($coupon['is_eligible'] ? 'color:var(--hover-color)' : ''); ?>">
                                                                <?php echo e($coupon['code']); ?>

                                                            </span>
                                                            
                                                        </div>
                                                        <?php if($coupon['is_eligible']): ?>
                                                        <div class="w-100">
                                                            <button type="button" class="btn-coupon-apply p-2" data-coupon-code="<?php echo e($coupon['code']); ?>" data-is-eligible="true" title="Apply Coupon"> Apply </button>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
	                <hr>
	                    <!-- SUMMARY LIST -->
                        <ul class="cart-summary-list">
                            <li class="cart-summary-item">
                                <span class="cart-summary-label">Subtotal:</span>
                                <span class="cart-summary-value">₹<?php echo e(number_format($cart->totals['subtotal'] ?? 0, 2)); ?></span>
                            </li>
                            <?php if(($cart->totals['discount'] ?? 0) > 0): ?>
                                <li class="cart-summary-item">
                                    <span class="cart-summary-label">Discount:</span>
                                    <span class="cart-summary-value cart-summary-discount">-₹<?php echo e(number_format($cart->totals['discount'], 2)); ?></span>
                                </li>
                            <?php endif; ?>
                            <li class="cart-summary-item">
                                <span class="cart-summary-label">Shipping:</span>
                                <span class="cart-summary-value">
                                    <?php
                                        $standardShipping = \App\Models\ShippingMethod::where('code', 'standard')->where('is_active', true)->first();
                                        $cartShipping = $cart->totals['shipping'] ?? 0;
                                    ?>
                                    <?php if($cartShipping == 0 && $standardShipping && $standardShipping->price > 0): ?>
                                        <span class="text-muted text-decoration-line-through">₹<?php echo e(number_format($standardShipping->price, 2)); ?></span>
                                        <span class="cart-summary-discount">FREE</span>
                                    <?php elseif($cartShipping == 0): ?>
                                        <span class="cart-summary-discount">FREE</span>
                                    <?php else: ?>
                                        ₹<?php echo e(number_format($cartShipping, 2)); ?>

                                    <?php endif; ?>
                                </span>
                            </li>
                            <li class="cart-summary-item cart-summary-total">
                                <span class="cart-summary-label">Total:</span>
                                <span class="cart-summary-value">₹<?php echo e(number_format($cart->totals['total'] ?? 0, 2)); ?></span>
                            </li>
                        </ul>
                        <?php
                            // Check stock availability for all items
                            $stockIssues = [];
                            $hasStockIssues = false;
                            
                            foreach ($cart->items as $item) {
                                $availableStock = 0;
                                $itemName = optional($item->product)->name ?? 'Product unavailable';
                                
                                if ($item->product_variant_id && $item->productVariant) {
                                    $availableStock = $item->productVariant->onlineAvailableStock();
                                    $itemName .= ' - ' . $item->productVariant->variation_name;
                                } elseif ($item->product) {
                                    $availableStock = $item->product->onlineAvailableStock();
                                } else {
                                    $availableStock = 0;
                                }
                                
                                if ($availableStock <= 0) {
                                    $stockIssues[] = [
                                        'name' => $itemName,
                                        'type' => 'out_of_stock',
                                        'available' => 0,
                                        'requested' => $item->qty
                                    ];
                                    $hasStockIssues = true;
                                } elseif ($availableStock < $item->qty) {
                                    $stockIssues[] = [
                                        'name' => $itemName,
                                        'type' => 'insufficient',
                                        'available' => $availableStock,
                                        'requested' => $item->qty
                                    ];
                                    $hasStockIssues = true;
                                }
                            }
                        ?>
                        <a href="<?php echo e(route('checkout.index')); ?>" 
                           class="btn-checkout <?php echo e($hasStockIssues ? 'disabled' : ''); ?>"
                           id="checkoutBtn"
                           <?php if($hasStockIssues): ?> 
                               onclick="validateStockBeforeCheckout(event); return false;"
                           <?php endif; ?>>
                            <i class="bi bi-arrow-right-circle"></i>
                            Proceed to Checkout
                        </a>
                        <?php if($hasStockIssues): ?>
                            <div class="alert alert-danger mt-2 mb-0" style="font-size: 0.9em;">
                                <i class="bi bi-exclamation-triangle-fill"></i>
                                <strong>Stock Issues Detected:</strong>
                                <ul class="mb-0 mt-2" style="padding-left: 1.5rem;">
                                    <?php $__currentLoopData = $stockIssues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $issue): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <li>
                                            <?php if($issue['type'] === 'out_of_stock'): ?>
                                                <strong><?php echo e($issue['name']); ?></strong> - Out of stock (You have <?php echo e($issue['requested']); ?> in cart)
                                            <?php else: ?>
                                                <strong><?php echo e($issue['name']); ?></strong> - Only <?php echo e($issue['available']); ?> available (You have <?php echo e($issue['requested']); ?> in cart)
                                            <?php endif; ?>
                                        </li>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </ul>
                                <p class="mb-0 mt-2"><strong>Please update quantities or remove items before checkout.</strong></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php else: ?>
        <div class="cart-empty-alert">
            <h4>
                <i class="bi bi-cart-x"></i>
                Your cart is empty!
            </h4>
            <p>Start shopping to add items to your cart.</p>
            <a href="<?php echo e(route('home')); ?>" class="btn-continue-shopping">
                <i class="bi bi-arrow-left"></i>
                Continue Shopping
            </a>
        </div>
    <?php endif; ?>
</div>
</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Cart line-item quantity: minus/plus buttons (delegated)
    const cartCard = document.querySelector('.cart-items-card');
    if (cartCard) {
        cartCard.addEventListener('click', function(e) {
            const minusBtn = e.target.closest('.cart-qty-minus');
            const plusBtn = e.target.closest('.cart-qty-plus');
            if (!minusBtn && !plusBtn) return;
            if (minusBtn && minusBtn.disabled) return;
            if (plusBtn && plusBtn.disabled) return;

            const form = (minusBtn || plusBtn).closest('.cart-qty-form');
            if (!form) return;
            const qtyInput = form.querySelector('input[name="qty"]');
            const qtyDisplay = form.querySelector('.cart-qty-value');
            const min = parseInt(form.dataset.min || '1', 10);
            const max = parseInt(form.dataset.max || '999', 10);
            let qty = parseInt(qtyInput.value || '1', 10);

            if (minusBtn) {
                qty = Math.max(min, qty - 1);
            } else {
                qty = Math.min(max, qty + 1);
            }
            qtyInput.value = qty;
            if (qtyDisplay) qtyDisplay.textContent = qty;
            form.submit();
        });
    }

    // Handle coupon card clicks - only for eligible coupons
    const couponButtons = document.querySelectorAll('.btn-coupon-apply');
    
    couponButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // Check if coupon is eligible
            const isEligible = this.dataset.isEligible === 'true';
            if (!isEligible) {
                return false;
            }
            
            const couponCard = this.closest('.coupon-card');
            const couponCode = this.dataset.couponCode;
            
            if (!couponCode) return;
            
            applyCoupon(couponCode, couponCard, this);
        });
    });

    // Prevent clicks on disabled coupon cards
    const disabledCouponCards = document.querySelectorAll('.coupon-card-disabled');
    disabledCouponCards.forEach(function(card) {
        card.addEventListener('click', function(e) {
            // Allow clicks on the button itself (handled above)
            if (e.target.closest('.btn-coupon-apply')) {
                return;
            }
            e.preventDefault();
            e.stopPropagation();
        });
    });

    function applyCoupon(code, couponCard, button) {
        // Show loading state
        if (button) {
            button.disabled = true;
            button.textContent = 'Applying...';
        }
        if (couponCard) {
            couponCard.classList.add('applying');
        }

        // Get CSRF token
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
            document.querySelector('input[name="_token"]')?.value ||
            document.querySelector('#coupon-form input[name="_token"]')?.value;

        // Create form data
        const formData = new FormData();
        formData.append('code', code);
        formData.append('_token', csrfToken);

        // Make AJAX request
        fetch('<?php echo e(route("cart.apply-coupon")); ?>', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Reload page to show updated cart with applied coupon
                window.location.reload();
            } else {
                // Show error message
                alert(data.message || 'Failed to apply coupon');
                
                // Reset button state
                if (button) {
                    button.disabled = false;
                    button.textContent = 'Apply';
                }
                if (couponCard) {
                    couponCard.classList.remove('applying');
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while applying the coupon. Please try again.');
            
            // Reset button state
            if (button) {
                button.disabled = false;
                button.textContent = 'Apply';
            }
            if (couponCard) {
                couponCard.classList.remove('applying');
            }
        });
    }
});

function toggleCoupons() {
    const list = document.getElementById('couponList');
    const arrow = document.getElementById('couponArrow');

    if (!list) return;

    if (list.style.display === 'none' || list.style.display === '') {
        list.style.display = 'block';
        arrow.classList.replace('bi-chevron-right', 'bi-chevron-down');
    } else {
        list.style.display = 'none';
        arrow.classList.replace('bi-chevron-down', 'bi-chevron-right');
    }
}

function trimText() {
    let elements = document.querySelectorAll('.cart-item-name');
    let width = window.innerWidth;

    let limit = 45; // default desktop
    if (width < 576) limit = 18;        // mobile
    else if (width < 992) limit = 25;   // tablet

    elements.forEach(el => {
        let fullText = el.getAttribute('title');
        if (fullText.length > limit) {
            el.textContent = fullText.substring(0, limit) + '...';
        } else {
            el.textContent = fullText;
        }
    });
}

window.onload = trimText;
window.onresize = trimText;
</script>
<?php $__env->stopSection(); ?>

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