<div class="section-title" style="padding-top:16px;">
    <span><i class="bi bi-bag me-1 text-accent"></i>Your Cart</span>
    <?php if (!empty($cart)): ?>
    <button onclick="clearCart()" style="background:none;border:none;color:var(--danger);font-size:.78rem;font-weight:700;cursor:pointer;">
        <i class="bi bi-trash me-1"></i>Clear
    </button>
    <?php endif; ?>
</div>

<?php if (empty($cart)): ?>
<div class="empty-state">
    <div class="empty-state-icon">🛒</div>
    <h4>Your cart is empty</h4>
    <p>Add items from the menu to get started</p>
    <a href="<?= url('shop') ?>" class="btn-main" style="width:auto;display:inline-flex;">Browse Menu</a>
</div>
<?php else: ?>

<!-- Cart items -->
<div class="cart-wrap" style="padding-bottom:0;">
    <?php foreach ($cart as $key => $item): ?>
    <div class="cart-item" id="ci-<?= e($key) ?>">
        <?php if (!empty($item['image'])): ?>
        <img class="cart-item-img" src="<?= e(upload_url($item['image'])) ?>" alt="<?= e($item['name']) ?>">
        <?php else: ?>
        <div class="cart-item-img-ph">🍽</div>
        <?php endif; ?>
        <div style="flex:1;min-width:0;">
            <div class="ci-name"><?= e($item['name']) ?></div>
            <?php if ($item['choices_label']): ?>
            <div class="ci-choices"><?= e($item['choices_label']) ?></div>
            <?php endif; ?>
            <div class="ci-price"><?= money($item['unit_price']) ?> each</div>
            <div class="qty-ctrl mt-2">
                <button onclick="updateCart('<?= e($key) ?>', <?= $item['qty'] - 1 ?>)">−</button>
                <span class="qv"><?= $item['qty'] ?></span>
                <button onclick="updateCart('<?= e($key) ?>', <?= $item['qty'] + 1 ?>)">+</button>
            </div>
        </div>
        <div style="text-align:right;flex-shrink:0;">
            <div style="font-size:.9rem;font-weight:800;"><?= money($item['unit_price'] * $item['qty']) ?></div>
            <button onclick="updateCart('<?= e($key) ?>', 0)"
                    style="background:none;border:none;color:var(--danger);font-size:.8rem;margin-top:6px;cursor:pointer;">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Voucher -->
<div style="padding:0 14px 12px;">
    <div class="s-card">
        <div class="s-card-title"><i class="bi bi-ticket-perforated"></i> Voucher Code</div>
        <div class="voucher-row">
            <input type="text" id="voucherInput" class="form-control" placeholder="Enter voucher code"
                   style="text-transform:uppercase;letter-spacing:1px;">
            <button class="voucher-btn" onclick="applyVoucher()">Apply</button>
        </div>
        <div id="voucherMsg" style="margin-top:8px;font-size:.78rem;"></div>
    </div>
</div>

<!-- Summary -->
<div style="padding:0 14px 120px;">
    <div class="order-summary">
        <div class="summary-row"><span>Subtotal</span><strong id="ss"><?= money($subtotal) ?></strong></div>
        <div class="summary-row" id="discRow" style="display:none;">
            <span style="color:var(--success);">Voucher Discount</span>
            <strong style="color:var(--success);" id="discVal">− Rs. 0.00</strong>
        </div>
        <div class="summary-divider"></div>
        <div class="summary-total">
            <span>Total</span>
            <span id="totalVal"><?= money($subtotal) ?></span>
        </div>
    </div>
    <a href="<?= url('shop/checkout') ?>" class="btn-main">
        <i class="bi bi-lock-fill me-2"></i>Proceed to Checkout
    </a>
</div>

<?php endif; ?>

<?php ob_start(); ?>
<script>
const _cartSubtotal = <?= $subtotal ?>;

async function updateCart(key, qty) {
    const fd = new FormData();
    fd.append('key', key); fd.append('qty', qty); fd.append('_csrf', _CSRF);
    const res  = await fetch('<?= url('shop/cart/update') ?>', { method:'POST', body:fd });
    const data = await res.json();
    if (data.success) { updateCartUI(data.cart_count, data.cart_total); location.reload(); }
}

function clearCart() {
    if (!confirm('Clear your entire cart?')) return;
    updateCart('__clear__', 0);
}

async function applyVoucher() {
    const code = document.getElementById('voucherInput').value.trim();
    const msg  = document.getElementById('voucherMsg');
    if (!code) return;
    const fd = new FormData();
    fd.append('code', code); fd.append('total', _cartSubtotal); fd.append('_csrf', _CSRF);
    const res  = await fetch('<?= url('shop/voucher/validate') ?>', { method:'POST', body:fd });
    const data = await res.json();
    if (data.valid) {
        msg.innerHTML = `<span style="color:var(--success);font-weight:700;"><i class="bi bi-check-circle me-1"></i>Saved Rs. ${data.discount.toFixed(2)}!</span>`;
        document.getElementById('discRow').style.display = '';
        document.getElementById('discVal').textContent   = '− Rs. ' + data.discount.toFixed(2);
        document.getElementById('totalVal').textContent  = 'Rs. ' + Math.max(0, _cartSubtotal - data.discount).toFixed(2);
        sessionStorage.setItem('voucher_code', code);
    } else {
        msg.innerHTML = `<span style="color:var(--danger);"><i class="bi bi-x-circle me-1"></i>${data.message}</span>`;
    }
}
</script>
<?php $extraJs = ob_get_clean(); ?>
