<?php
/** @var array $carrito */
$carrito = $carrito ?? [
    'items' => [],
    'subtotal' => 0.0,
    'descuento_pct' => 0.0,
    'descuento_monto' => 0.0,
    'total' => 0.0,
];

$totalItems = 0;
foreach ($carrito['items'] as $item) {
    $totalItems += (int)($item['cantidad'] ?? 0);
}
?>

<button type="button" class="cart-fab" id="cart-fab">
    🛒 Ver carrito
    <span class="cart-fab-badge"
          id="cart-fab-badge"
          <?= $totalItems==0 ? 'style="display:none;"':'' ?>>
        <?= $totalItems ?>
    </span>
</button>

<div class="cp-overlay" id="cart-overlay"></div>

<aside class="cp-drawer cart-drawer" id="cart-drawer" aria-hidden="true">

    <div class="cp-drawer-header">

        <div>
            <h3>Tu carrito</h3>
            <span class="cp-drawer-sub">
                Revisa tus productos antes de pagar
            </span>
        </div>

        <button
            type="button"
            class="cp-drawer-close"
            id="cart-drawer-close">
            ✕
        </button>

    </div>

    <div class="cp-drawer-body">

        <div id="cart-items-container">

        <?php if(empty($carrito['items'])): ?>

            <div class="empty-state">

                <div style="font-size:55px;">🍿</div>

                <h4>Tu carrito está vacío</h4>

                <p>
                    Agrega productos para comenzar tu compra.
                </p>

            </div>

        <?php else: ?>

            <?php foreach($carrito['items'] as $item): ?>

            <div class="cart-item"
                 data-cart-line-key="<?= esc($item['line_key']) ?>">

                <div class="cart-item-thumb">

                    <img
                        src="<?= esc($item['imagen_url']) ?>"
                        alt="<?= esc($item['nombre']) ?>">

                </div>

                <div class="cart-item-content">

                    <div class="cart-item-top">

                        <div class="cart-item-info">

                            <h4>
                                <?= esc($item['nombre']) ?>
                            </h4>

                            <?php if(!empty($item['id_promocion'])): ?>

                                <span class="promo-badge">
                                    🏷 Promoción aplicada
                                </span>

                            <?php endif; ?>

                            <div class="cart-price">

                                Precio unitario

                                <strong>
                                    S/
                                    <?= number_format($item['precio_unitario'],2) ?>
                                </strong>

                            </div>

                        </div>

                        <button
                            class="remove-item"
                            type="button"
                            data-line-key="<?= esc($item['line_key']) ?>">
                            Eliminar
                        </button>

                    </div>

                    <div class="cart-item-bottom">

                         <div class="cart-item-left">

                            <div class="qty-stepper">

                                <button
                                    type="button"
                                    class="qty-btn qty-minus"
                                    data-line-key="<?= esc($item['line_key']) ?>">
                                    −
                                </button>

                                <input
                                    class="quantity-input"
                                    type="number"
                                    min="1"
                                    value="<?= esc($item['cantidad']) ?>"
                                    data-line-key="<?= esc($item['line_key']) ?>">

                                <button
                                    type="button"
                                    class="qty-btn qty-plus"
                                    data-line-key="<?= esc($item['line_key']) ?>">
                                    +
                                </button>

                            </div>

                            <button
                                class="remove-item"
                                type="button"
                                data-line-key="<?= esc($item['line_key']) ?>">
                                🗑 Eliminar
                            </button>

                        </div>

                        <div class="cart-subtotal">

                            <span>Subtotal</span>

                            <strong>
                                S/ <?= number_format($item['subtotal'],2) ?>
                            </strong>

                        </div>


                    </div>

                </div>

            </div>

            <?php endforeach; ?>

        <?php endif; ?>

        </div>

    </div>

    <div class="cp-drawer-footer">

        <div
            class="cart-totals"
            id="cart-totals">

            <div>

                <span>Subtotal</span>

                <span>
                    S/
                    <?= number_format($carrito['subtotal'],2) ?>
                </span>

            </div>

            <?php if($carrito['descuento_pct']>0): ?>

            <div>

                <span>
                    Descuento
                    <?= $carrito['descuento_pct'] ?>%
                </span>

                <span class="discount">

                    - S/
                    <?= number_format($carrito['descuento_monto'],2) ?>

                </span>

            </div>

            <?php endif; ?>

            <div class="summary-total">

                <strong>Total</strong>

                <strong class="summary-price">

                    S/
                    <?= number_format($carrito['total'],2) ?>

                </strong>

            </div>

        </div>

        <div class="cart-actions">

            <a
                href="<?= base_url('alimentos/pago') ?>"
                id="checkout-link"
                <?= empty($carrito['items'])
                    ? 'style="opacity:.5;pointer-events:none;"'
                    : '' ?>>

                Ir a pagar

            </a>

        </div>

    </div>

</aside>

<script>
(function () {
    var cartContainer = document.getElementById('cart-items-container');
    var checkoutLink  = document.getElementById('checkout-link');
    var cartFab       = document.getElementById('cart-fab');
    var cartFabBadge  = document.getElementById('cart-fab-badge');
    var cartOverlay   = document.getElementById('cart-overlay');
    var cartDrawer    = document.getElementById('cart-drawer');
    var cartDrawerClose = document.getElementById('cart-drawer-close');
    var cartTotals    = document.getElementById('cart-totals');

    var URLS = {
        actualizar: '<?= base_url('alimentos/carrito/actualizar') ?>',
        eliminar: '<?= base_url('alimentos/carrito/eliminar') ?>'
    };

    function openCart() {
        cartOverlay.classList.add('is-open');
        cartDrawer.classList.add('is-open');
        cartDrawer.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
    }

    function closeCart() {
        cartOverlay.classList.remove('is-open');
        cartDrawer.classList.remove('is-open');
        cartDrawer.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
    }

    cartFab.addEventListener('click', openCart);
    cartDrawerClose.addEventListener('click', closeCart);
    cartOverlay.addEventListener('click', function (e) {
        if (e.target === cartOverlay) closeCart();
    });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') closeCart();
    });

    function escapeHtml(value) {
        var div = document.createElement('div');
        div.textContent = value === null || value === undefined ? '' : String(value);
        return div.innerHTML;
    }

    function renderCart(cart) {

    var items = cart && cart.items ? cart.items : {};
    var keys = Object.keys(items);

    if (keys.length === 0) {

        cartContainer.innerHTML =
            '<div class="empty-state">' +
                '<div style="font-size:55px;">🍿</div>' +
                '<h4>Tu carrito está vacío</h4>' +
                '<p>Agrega productos para comenzar tu compra.</p>' +
            '</div>';

        checkoutLink.style.opacity = '.5';
        checkoutLink.style.pointerEvents = 'none';

    } else {

        checkoutLink.style.opacity = '';
        checkoutLink.style.pointerEvents = '';

        var html = '';

        keys.forEach(function(key){

            var item = items[key];

            html +=

            '<div class="cart-item" data-cart-line-key="'+escapeHtml(key)+'">'+

                '<div class="cart-item-thumb">'+
                    '<img src="'+escapeHtml(item.imagen_url)+'" alt="">'+
                '</div>'+

                '<div class="cart-item-content">'+

                    '<div class="cart-item-top">'+

                        '<div class="cart-item-info">'+

                            '<h4>'+escapeHtml(item.nombre)+'</h4>'+

                            (item.id_promocion
                                ? '<span class="promo-badge">🏷 Promoción aplicada</span>'
                                : '')+

                            '<div class="cart-price">'+
                                'Precio unitario '+
                                '<strong>S/ '+Number(item.precio_unitario).toFixed(2)+'</strong>'+
                            '</div>'+

                        '</div>'+

                        '<button class="remove-item" data-line-key="'+escapeHtml(key)+'">'+
                            'Eliminar'+
                        '</button>'+

                    '</div>'+

                    '<div class="cart-item-bottom">'+

                        '<div class="cart-item-left">'+

                            '<div class="qty-stepper">'+

                                '<button class="qty-btn qty-minus" data-line-key="'+escapeHtml(key)+'">−</button>'+

                                '<input class="quantity-input" type="number" min="1" value="'+item.cantidad+'" data-line-key="'+escapeHtml(key)+'">'+

                                '<button class="qty-btn qty-plus" data-line-key="'+escapeHtml(key)+'">+</button>'+

                            '</div>'+

                            '<button class="remove-item" data-line-key="'+escapeHtml(key)+'">Eliminar</button>'+

                        '</div>'+

                        '<div class="cart-subtotal">'+

                            '<span>Subtotal</span>'+

                            '<strong>S/ '+Number(item.subtotal).toFixed(2)+'</strong>'+

                        '</div>'+

                    '</div>'

                '</div>'+

            '</div>';

        });

        cartContainer.innerHTML = html;
    }

    cartTotals.innerHTML =

        '<div>' +
            '<span>Subtotal</span>' +
            '<span>S/ '+Number(cart.subtotal||0).toFixed(2)+'</span>' +
        '</div>' +

        (cart.descuento_pct>0

            ? '<div>' +
                '<span>Descuento '+cart.descuento_pct+'%</span>' +
                '<span class="discount">- S/ '+Number(cart.descuento_monto).toFixed(2)+'</span>' +
              '</div>'

            : ''

        ) +

        '<div class="summary-total">' +

            '<strong>Total</strong>' +

            '<strong class="summary-price">' +

                'S/ '+Number(cart.total||0).toFixed(2)+

            '</strong>' +

        '</div>';

    var totalQty = 0;

    keys.forEach(function(key){

        totalQty += parseInt(items[key].cantidad)||0;

    });

    if(totalQty>0){

        cartFabBadge.style.display='';

        cartFabBadge.textContent=totalQty;

    }else{

        cartFabBadge.style.display='none';

    }

    document.dispatchEvent(
        new CustomEvent('cinecart:updated',{detail:cart})
    );

    }

    function modifyCart(url, data) {
        fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
            body: new URLSearchParams(data)
        })
            .then(function (r) { return r.json(); })
            .then(function (result) {
                if (result.success) {
                    if (result.cart) renderCart(result.cart);
                } else {
                    alert(result.message || 'No se pudo actualizar el carrito.');
                }
            })
            .catch(function () {
                alert('Ocurrió un error al actualizar el carrito.');
            });
    }

    cartContainer.addEventListener('click', function (event) {
        var target = event.target;
        if (target.matches('.remove-item')) {
            modifyCart(URLS.eliminar, { line_key: target.dataset.lineKey });
        } else if (target.matches('.qty-plus') || target.matches('.qty-minus')) {
            var row = target.closest('.cart-item');
            var input = row ? row.querySelector('.quantity-input') : null;
            if (!input) return;
            var current = parseInt(input.value, 10) || 1;
            var next = target.matches('.qty-plus') ? current + 1 : Math.max(1, current - 1);
            input.value = next;
            modifyCart(URLS.actualizar, { line_key: target.dataset.lineKey, cantidad: next });
        }
    });

    cartContainer.addEventListener('change', function (event) {
        if (event.target.matches('.quantity-input')) {
            var cantidad = parseInt(event.target.value, 10) || 1;
            modifyCart(URLS.actualizar, { line_key: event.target.dataset.lineKey, cantidad: cantidad });
        }
    });

    // Expuesto para que otras páginas (promociones, pago de alimentos/membresía)
    // puedan abrir el carrito o refrescar su contenido tras sus propias
    // llamadas AJAX (ej. "Agregar al carrito" de una promoción).
    window.CineCart = {
        open: openCart,
        close: closeCart,
        refresh: renderCart
    };
})();
</script>
