{% extends 'base.html' %}
{% block title %}POS | Cashier Interface{% endblock %}

{% block extra_css %}
.menu-item-card {
    cursor: pointer;
    transition: all 0.2s;
}
.menu-item-card:hover {
    border-color: var(--orange);
    background-color: #2a2a2d;
}
.cart-sticky {
    position: sticky;
    top: 90px;
    max-height: calc(100vh - 120px);
    overflow-y: auto;
}
.cart-item {
    border-bottom: 1px solid var(--slate);
    padding: 10px 0;
}
.cart-item:last-child {
    border-bottom: none;
}
{% endblock %}

{% block content %}
<div class="row g-4">
    <!-- Menu Section -->
    <div class="col-lg-8">
        <h2 class="mb-4 fw-bold">Menu</h2>
        <div class="row g-3">
            {% for item in menu_items %}
            <div class="col-md-4">
                <div class="card h-100 menu-item-card shadow-sm" onclick="addToCart({{ item.id }}, '{{ item.name }}', {{ item.price }})">
                    <div class="card-body text-center py-4">
                        <h5 class="fw-bold mb-1">{{ item.name }}</h5>
                        <p class="text-orange fw-bold mb-0" style="color: var(--orange);">{{ item.price }} EGP</p>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Cart Section -->
    <div class="col-lg-4">
        <div class="card cart-sticky shadow-lg">
            <div class="card-header py-3">
                <h4 class="mb-0 fw-bold"><i class="bi bi-receipt me-2"></i> Current Order</h4>
            </div>
            <div class="card-body">
                <div id="cart-items" class="mb-4">
                    <p class="text-center text-secondary py-4" id="empty-cart-msg">Cart is empty</p>
                </div>
                
                <div class="mb-3">
                    <label class="form-label small text-secondary">Customer Notes / Customization</label>
                    <textarea id="customer-notes" class="form-control bg-dark text-white border-secondary" rows="2" placeholder="e.g., No onion, extra spicy..."></textarea>
                </div>

                <div class="d-flex justify-content-between mb-2">
                    <span class="text-secondary">Subtotal</span>
                    <span id="subtotal">0.00 EGP</span>
                </div>
                <div class="d-flex justify-content-between mb-4 border-top pt-2">
                    <h4 class="fw-bold">Total</h4>
                    <h4 class="fw-bold" id="total" style="color: var(--orange);">0.00 EGP</h4>
                </div>

                <button class="btn btn-primary w-100 py-3 fw-bold" onclick="completeOrder()" id="checkout-btn" disabled>
                    COMPLETE ORDER
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="card w-100">
            <div class="card-body text-center py-5">
                <div class="display-1 text-success mb-4"><i class="bi bi-check-circle"></i></div>
                <h2 class="fw-bold mb-3">Order Completed!</h2>
                <p class="text-secondary mb-4" id="order-confirm-msg"></p>
                <div class="d-grid gap-2">
                    <a id="print-receipt-btn" href="#" class="btn btn-primary" target="_blank">PRINT RECEIPT</a>
                    <button type="button" class="btn btn-outline-light" onclick="location.reload()">NEW ORDER</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let cart = {};

    function addToCart(id, name, price) {
        if (cart[id]) {
            cart[id].quantity += 1;
        } else {
            cart[id] = { id, name, price, quantity: 1 };
        }
        renderCart();
    }

    function removeFromCart(id) {
        if (cart[id]) {
            if (cart[id].quantity > 1) {
                cart[id].quantity -= 1;
            } else {
                delete cart[id];
            }
        }
        renderCart();
    }

    function renderCart() {
        const cartItemsDiv = document.getElementById('cart-items');
        const emptyMsg = document.getElementById('empty-cart-msg');
        const checkoutBtn = document.getElementById('checkout-btn');
        
        cartItemsDiv.innerHTML = '';
        let total = 0;
        let itemCount = 0;

        for (const id in cart) {
            const item = cart[id];
            itemCount += item.quantity;
            total += item.price * item.quantity;

            const itemDiv = document.createElement('div');
            itemDiv.className = 'cart-item d-flex justify-content-between align-items-center';
            itemDiv.innerHTML = `
                <div>
                    <h6 class="mb-0 fw-bold">${item.name}</h6>
                    <small class="text-secondary">${item.price} x ${item.quantity}</small>
                </div>
                <div class="d-flex align-items-center">
                    <span class="fw-bold me-3">${(item.price * item.quantity).toFixed(2)}</span>
                    <button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(${id})"><i class="bi bi-dash"></i></button>
                </div>
            `;
            cartItemsDiv.appendChild(itemDiv);
        }

        if (itemCount > 0) {
            emptyMsg.style.display = 'none';
            checkoutBtn.disabled = false;
        } else {
            cartItemsDiv.appendChild(emptyMsg);
            emptyMsg.style.display = 'block';
            checkoutBtn.disabled = true;
        }

        document.getElementById('subtotal').innerText = total.toFixed(2) + ' EGP';
        document.getElementById('total').innerText = total.toFixed(2) + ' EGP';
    }

    async function completeOrder() {
        const btn = document.getElementById('checkout-btn');
        const notes = document.getElementById('customer-notes').value;
        btn.disabled = true;
        btn.innerText = 'PROCESSING...';

        const cartArray = Object.values(cart);
        
        try {
            const response = await fetch('{% url "create_order" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({ cart: cartArray, notes: notes })
            });

            const result = await response.json();
            if (result.success) {
                document.getElementById('order-confirm-msg').innerText = 'Order #' + result.order_number + ' has been successfully placed and stock has been updated.';
                document.getElementById('print-receipt-btn').href = '/receipt/' + result.order_number + '/';
                const modal = new bootstrap.Modal(document.getElementById('successModal'));
                modal.show();
            } else {
                alert('Error: ' + result.error);
                btn.disabled = false;
                btn.innerText = 'COMPLETE ORDER';
            }
        } catch (error) {
            alert('Something went wrong. Please check stock levels.');
            btn.disabled = false;
            btn.innerText = 'COMPLETE ORDER';
        }
    }
</script>
{% endblock %}
