<?php $__env->startSection('title', 'Keranjang Belanja'); ?>

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

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">

    <!-- HEADER -->
    <div class="mb-8 flex items-center justify-between">
        <a href="<?php echo e(route('customer.dashboard')); ?>" class="inline-flex items-center gap-2 text-sm font-medium text-gray-500 hover:text-primary bg-white px-4 py-2 rounded-full border border-gray-200 hover:border-gray-300 transition-all shadow-sm">
            <i class="bi bi-arrow-left"></i> Kembali
        </a>
        <h1 class="text-2xl font-extrabold text-primary tracking-tight hidden sm:block">Keranjang Belanja</h1>
    </div>

    <!-- NOTIFIKASI -->
    <?php if(session('success')): ?>
        <div class="bg-green-50 text-green-700 border border-green-200 rounded-xl p-4 flex items-center gap-3 mb-6 font-medium text-sm">
            <i class="bi bi-check-circle-fill text-green-500 text-lg"></i>
            <?php echo e(session('success')); ?>

        </div>
    <?php endif; ?>

    <?php if(session('error')): ?>
        <div class="bg-red-50 text-red-700 border border-red-200 rounded-xl p-4 flex items-center gap-3 mb-6 font-medium text-sm">
            <i class="bi bi-exclamation-triangle-fill text-red-500 text-lg"></i>
            <?php echo e(session('error')); ?>

        </div>
    <?php endif; ?>

    <?php if($items->isEmpty()): ?>
        <!-- EMPTY STATE -->
        <div class="bg-white border border-gray-100 rounded-3xl shadow-sm p-12 text-center">
            <div class="w-24 h-24 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="bi bi-cart-x text-5xl text-gray-300"></i>
            </div>
            <h2 class="text-2xl font-bold text-primary mb-2">Keranjang masih kosong</h2>
            <p class="text-secondary mb-8">Yuk temukan produk favorit Anda dan mulai berbelanja sekarang!</p>
            <a href="<?php echo e(route('customer.dashboard')); ?>" class="inline-flex items-center gap-2 bg-primary text-white font-bold py-3 px-8 rounded-full hover:bg-gray-800 transition transform hover:scale-105 shadow-lg shadow-gray-200">
                <i class="bi bi-shop"></i> Mulai Belanja
            </a>
        </div>
    <?php else: ?>
        <!-- CART LAYOUT -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            
            <!-- LEFT: CART ITEMS (8 cols on lg) -->
            <div class="lg:col-span-8 space-y-4">
                
                <!-- SELECT ALL BAR -->
                <div class="bg-white rounded-2xl flex items-center justify-between p-4 px-6 border border-gray-100 shadow-sm">
                    <h2 class="font-bold text-gray-800 text-sm">Produk dalam Keranjang</h2>
                    <label class="flex items-center gap-3 cursor-pointer text-sm text-gray-600 font-medium select-none group">
                        <input type="checkbox" id="select-all-checkbox" class="w-5 h-5 rounded border-gray-300 text-accent focus:ring-accent accent-accent transition cursor-pointer">
                        <span class="group-hover:text-primary transition">Pilih Semua</span>
                    </label>
                </div>

                <!-- ITEMS KONTENER -->
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm divide-y divide-gray-100 overflow-hidden" id="cart-items-container">
                    <?php $__currentLoopData = $items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $varian = $item->varian;
                        $produk = $varian ? $varian->produk : $item->produk;
                        $harga = $varian ? $varian->harga : ($item->produk->varians->first()->harga ?? 0);
                        $stok = $varian ? $varian->stok : ($item->produk->varians->first()->stok ?? 0);
                        $ukuran = $varian ? $varian->ukuran : '-';
                        $warna = $varian ? $varian->warna : '-';
                        $foto = $produk->foto;
                        $kategoriNama = $produk->kategori->nama ?? 'Produk';
                        $produkNama = $produk->nama;
                        $produkId = $produk->id;
                    ?>
                    
                    <div class="cart-item p-4 sm:p-6 flex flex-col sm:flex-row gap-4 sm:gap-6 hover:bg-gray-50 transition relative group"
                         data-item-id="<?php echo e($item->id); ?>" 
                         data-price="<?php echo e($harga); ?>" 
                         data-qty="<?php echo e($item->jumlah); ?>"
                         data-stok="<?php echo e($stok); ?>">
                        
                        <!-- Checkbox Desktop/Mobile terpadu di desain ini -->
                        <div class="flex gap-4 w-full sm:w-auto">
                            <div class="pt-2">
                                <input type="checkbox"
                                       class="item-checkbox w-5 h-5 rounded border-gray-300 text-accent focus:ring-accent accent-accent transition cursor-pointer"
                                       data-item-id="<?php echo e($item->id); ?>"
                                       data-price="<?php echo e($harga); ?>">
                            </div>

                            <a href="<?php echo e(route('customer.produk.show', $produkId)); ?>" class="block shrink-0 rounded-xl overflow-hidden border border-gray-200 bg-gray-50 w-20 h-20 sm:w-24 sm:h-24 relative isolate">
                                <?php if($foto): ?>
                                    <img src="<?php echo e(asset('storage/' . $foto)); ?>" alt="<?php echo e($produkNama); ?>" class="w-full h-full object-cover transition duration-300 group-hover:scale-110">
                                <?php else: ?>
                                    <div class="w-full h-full flex items-center justify-center">
                                        <i class="bi bi-image text-gray-300 text-3xl"></i>
                                    </div>
                                <?php endif; ?>
                            </a>
                        </div>

                        <!-- INFO -->
                        <div class="flex-1 flex flex-col justify-between">
                            <div>
                                <div class="text-[10px] font-bold tracking-widest text-gray-400 uppercase mb-1"><?php echo e($kategoriNama); ?></div>
                                <a href="<?php echo e(route('customer.produk.show', $produkId)); ?>" class="text-base font-semibold text-primary hover:text-accent transition line-clamp-2 leading-tight mb-2">
                                    <?php echo e($produkNama); ?>

                                </a>
                                <div class="text-xs font-medium text-gray-500 bg-gray-100 inline-block px-2 py-1 rounded">
                                    Varian: <?php echo e($ukuran); ?> &middot; <?php echo e($warna); ?>

                                </div>
                            </div>
                            
                            <div class="flex items-center justify-between mt-4">
                                <div>
                                    <div class="text-lg font-bold text-gray-900">Rp <?php echo e(number_format($harga, 0, ',', '.')); ?></div>
                                    <div class="text-xs font-medium <?php echo e($stok < 5 ? 'text-orange-500' : 'text-green-600'); ?> mt-1">Stok: <?php echo e($stok); ?></div>
                                </div>
                                <div class="hidden sm:block text-right">
                                    <div class="text-[10px] uppercase tracking-wider text-gray-400 font-bold mb-1">Subtotal</div>
                                    <div class="text-base font-bold text-primary subtotal-display" id="subtotal-<?php echo e($item->id); ?>">
                                        Rp <?php echo e(number_format($harga * $item->jumlah, 0, ',', '.')); ?>

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

                        <!-- ACTIONS (Qty & Delete) -->
                        <div class="flex flex-row sm:flex-col justify-between sm:justify-end items-center sm:items-end gap-3 w-full sm:w-auto border-t sm:border-0 border-gray-100 pt-4 sm:pt-0 mt-2 sm:mt-0">
                            
                            <div class="flex items-center bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm">
                                <button type="button" class="w-9 h-9 flex items-center justify-center text-gray-500 hover:bg-gray-50 hover:text-primary transition" onclick="adjustQty(<?php echo e($item->id); ?>, -1, <?php echo e($stok); ?>)">
                                    <i class="bi bi-dash"></i>
                                </button>
                                <input type="number" value="<?php echo e($item->jumlah); ?>" min="1" max="<?php echo e($stok); ?>" id="qty-<?php echo e($item->id); ?>" onchange="updateQty(<?php echo e($item->id); ?>, this.value)" class="qty-input w-12 h-9 border-x border-gray-200 border-y-0 text-center text-sm font-semibold text-gray-800 p-0 focus:ring-0 focus:border-gray-200 appearance-none bg-white">
                                <button type="button" class="w-9 h-9 flex items-center justify-center text-gray-500 hover:bg-gray-50 hover:text-primary transition" onclick="adjustQty(<?php echo e($item->id); ?>, 1, <?php echo e($stok); ?>)">
                                    <i class="bi bi-plus"></i>
                                </button>
                            </div>

                            <button type="button" class="text-gray-400 hover:text-red-500 bg-white hover:bg-red-50 border border-gray-200 hover:border-red-200 w-9 h-9 rounded-lg flex items-center justify-center transition shadow-sm" title="Hapus" onclick="deleteItem(<?php echo e($item->id); ?>)">
                                <i class="bi bi-trash3 text-sm"></i>
                            </button>
                        </div>

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

            <!-- RIGHT: SUMMARY (4 cols on lg) -->
            <div class="lg:col-span-4 self-start sticky top-24">
                <div class="bg-white rounded-2xl border border-gray-100 p-6 shadow-[0_8px_30px_rgb(0,0,0,0.04)]">
                    <h3 class="text-lg font-bold text-primary mb-6 flex items-center gap-2">
                        <i class="bi bi-receipt"></i> Ringkasan Pesanan
                    </h3>
                    
                    <div id="summary-content">
                        <!-- Konten diisi JavaScript -->
                        <div class="text-center py-6 text-gray-400">
                            <i class="bi bi-check-circle text-4xl mb-3 block opacity-50"></i>
                            <p class="text-sm font-medium">Belum ada item yang dipilih</p>
                            <p class="text-xs mt-1">Centang produk yang ingin dibeli</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    <?php endif; ?>
</div>

<!-- TOAST -->
<div id="toast" class="fixed bottom-5 right-5 bg-green-500 text-white px-6 py-3 rounded-xl shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-2 pointer-events-none">
    <i class="bi bi-check-circle-fill"></i>
    <span id="toastMsg">Notifikasi</span>
</div>

<!-- SCRIPTS -->
<script>
// Format Rupiah
function formatRupiah(angka) {
    return new Intl.NumberFormat('id-ID').format(angka);
}

// Notification Toast
function showNotification(message, type = 'success') {
    const toast = document.getElementById('toast');
    const toastIcon = toast.querySelector('i');
    
    if (type === 'error') {
        toast.className = 'fixed bottom-5 right-5 bg-red-500 text-white px-6 py-3 rounded-xl shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 flex items-center gap-3 pointer-events-none';
        toastIcon.className = 'bi bi-x-circle-fill';
    } else {
        toast.className = 'fixed bottom-5 right-5 bg-gray-900 text-white px-6 py-3 rounded-xl shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 z-50 flex items-center gap-3 pointer-events-none';
        toastIcon.className = 'bi bi-check-circle-fill text-green-400';
    }
    
    document.getElementById('toastMsg').innerText = message;
    
    setTimeout(() => {
        toast.classList.replace('translate-y-0', 'translate-y-10');
        toast.classList.replace('opacity-100', 'opacity-0');
    }, 3000);
}

let selectedItems = new Map();

function updateSummary() {
    let totalItems = 0;
    let totalPrice = 0;
    let selectedItemsData = [];

    for (let [itemId, data] of selectedItems.entries()) {
        totalItems += data.qty;
        totalPrice += data.subtotal;
        selectedItemsData.push({
            cart_item_id: itemId,
            quantity: data.qty
        });
    }

    const summaryContainer = document.getElementById('summary-content');

    if (totalItems === 0) {
        summaryContainer.innerHTML = `
            <div class="text-center py-6 text-gray-400">
                <i class="bi bi-check2-square text-4xl mb-3 block opacity-50"></i>
                <p class="text-sm font-medium text-gray-500">Belum ada item yang dipilih</p>
            </div>
        `;
        return;
    }

    summaryContainer.innerHTML = `
        <div class="space-y-3 mb-6 font-medium text-sm text-gray-600">
            <div class="flex justify-between">
                <span>Total Item (${totalItems})</span>
                <span class="text-gray-900 font-bold">Rp ${formatRupiah(totalPrice)}</span>
            </div>
            <div class="flex justify-between text-green-600">
                <span>Bebas Ongkir</span>
                <span class="font-bold">Gratis!</span>
            </div>
        </div>
        <div class="border-t border-gray-100 pt-4 mb-6">
            <div class="flex justify-between items-center">
                <span class="text-gray-900 font-bold">Total Pembayaran</span>
                <span class="text-xl font-extrabold text-accentDark">Rp ${formatRupiah(totalPrice)}</span>
            </div>
        </div>
        <button id="btn-checkout" type="button" class="w-full bg-primary text-white font-bold py-4 rounded-xl shadow-lg shadow-gray-200 hover:bg-gray-800 hover:-translate-y-0.5 transition flex justify-center items-center gap-2" onclick="processCheckout()">
            <i class="bi bi-lock-fill text-gray-400"></i> Checkout Sekarang
        </button>
    `;
    
    window.selectedCheckoutItems = selectedItemsData;
}

function updateQty(itemId, newQty) {
    newQty = parseInt(newQty);
    if (isNaN(newQty) || newQty < 1) return;

    const cartItem = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
    const price = parseInt(cartItem.dataset.price);
    const maxStok = parseInt(cartItem.dataset.stok);
    
    if (newQty > maxStok) {
        showNotification(`Stok hanya tersisa ${maxStok} item`, 'error');
        document.getElementById(`qty-${itemId}`).value = maxStok;
        newQty = maxStok;
    }
    
    const newSubtotal = price * newQty;
    const subtotalElement = document.getElementById(`subtotal-${itemId}`);
    if (subtotalElement) {
        subtotalElement.innerText = `Rp ${formatRupiah(newSubtotal)}`;
    }

    cartItem.dataset.qty = newQty;

    const checkbox = cartItem.querySelector('.item-checkbox');
    if (checkbox && checkbox.checked) {
        selectedItems.set(itemId.toString(), { price: price, qty: newQty, subtotal: newSubtotal });
        updateSummary();
    }

    fetch('/cart/item/' + itemId, {
        method: 'PATCH',
        headers: {
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ jumlah: newQty })
    }).then(res => res.json()).then(data => {
        if (!data.success) showNotification(data.message || 'Gagal update qty', 'error');
    });
}

function adjustQty(itemId, delta, maxStok) {
    const input = document.getElementById(`qty-${itemId}`);
    if (!input) return;
    
    let val = parseInt(input.value) + delta;
    if (val < 1) val = 1;
    if (val > maxStok) {
        showNotification(`Stok hanya tersisa ${maxStok} item`, 'error');
        val = maxStok;
    }

    if (val !== parseInt(input.value)) {
        input.value = val;
        updateQty(itemId, val);
    }
}

function deleteItem(itemId) {
    if (!confirm('Hapus produk ini dari keranjang?')) return;

    fetch('/cart/item/' + itemId, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(res => res.json()).then(data => {
        if (data.success) {
            const itemEl = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
            if(itemEl) itemEl.remove();
            
            selectedItems.delete(itemId.toString());
            updateSummary();
            
            if(document.querySelectorAll('.cart-item').length === 0) {
                location.reload();
            } else {
                showNotification('Item dihapus!', 'success');
                updateCartBadge();
            }
        }
    });
}

function processCheckout() {
    const dataToSend = window.selectedCheckoutItems;
    if(!dataToSend || dataToSend.length === 0) {
        showNotification('Silakan pilih minimal 1 item untuk checkout.', 'error');
        return;
    }

    const btn = document.getElementById('btn-checkout');
    const oriText = btn.innerHTML;
    btn.innerHTML = `<i class="bi bi-arrow-repeat animate-spin"></i> Memproses...`;
    btn.disabled = true;

    fetch('<?php echo e(route("pesanan.process_checkout")); ?>', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ selected_items: dataToSend })
    }).then(res => res.json()).then(data => {
        if (data.success) {
            window.location.href = data.redirect_url;
        } else {
            showNotification(data.message || 'Gagal memproses checkout', 'error');
            btn.innerHTML = oriText;
            btn.disabled = false;
        }
    }).catch(err => {
        showNotification('Kesalahan jaringan saat checkout', 'error');
        btn.innerHTML = oriText;
        btn.disabled = false;
    });
}

function updateCartBadge() {
    fetch("<?php echo e(route('cart.count')); ?>")
        .then(res => res.json())
        .then(data => {
            const cartLink = document.querySelector('a[href*="keranjang"]');
            if(cartLink) {
                let badge = cartLink.querySelector('span');
                if(!badge && data.cartCount > 0) {
                    badge = document.createElement('span');
                    badge.className = "absolute -top-1 -right-2 bg-red-500 text-white text-[10px] w-4 h-4 flex items-center justify-center rounded-full";
                    cartLink.appendChild(badge);
                }
                if(badge) {
                    if (data.cartCount > 0) {
                        badge.style.display = 'flex';
                        badge.innerText = data.cartCount;
                    } else {
                        badge.style.display = 'none';
                    }
                }
            }
        });
}

document.addEventListener('DOMContentLoaded', () => {
    const checkboxes = document.querySelectorAll('.item-checkbox');
    const selectAllCheckbox = document.getElementById('select-all-checkbox');

    checkboxes.forEach(cb => {
        const cartItem = cb.closest('.cart-item');
        const itemId = cartItem.dataset.itemId;
        const price = parseInt(cartItem.dataset.price);
        const qty = parseInt(document.getElementById(`qty-${itemId}`).value);

        cb.addEventListener('change', function() {
            const curQty = parseInt(document.getElementById(`qty-${itemId}`).value);
            if(this.checked) {
                selectedItems.set(itemId.toString(), {price: price, qty: curQty, subtotal: price * curQty});
            } else {
                selectedItems.delete(itemId.toString());
            }
            updateSummary();
        });
    });

    if(selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            checkboxes.forEach(cb => {
                if(cb.checked !== isChecked) {
                    cb.checked = isChecked;
                    cb.dispatchEvent(new Event('change'));
                }
            });
        });
    }

    updateSummary();
    
    // Styling input number hilangkan arrow bawaan
    const styling = document.createElement('style');
    styling.innerHTML = `
        input[type="number"]::-webkit-inner-spin-button, 
        input[type="number"]::-webkit-outer-spin-button { 
            -webkit-appearance: none; margin: 0; 
        }
        input[type="number"] { -moz-appearance: textfield; }
        .qty-input:focus { outline: none; box-shadow: none; }
    `;
    document.head.appendChild(styling);
});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.customer', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\Toko-miftah\resources\views/keranjang/index.blade.php ENDPATH**/ ?>