{% extends 'base.html' %}
{% block title %}POS | Searing Sandwiches{% endblock %}

{% block extra_css %}
<style>
    .menu-item-card {
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 1px solid var(--border-soft);
        border-radius: 20px;
        background: white;
        height: 100%;
        overflow: hidden;
    }
    .menu-item-card:hover {
        border-color: var(--primary-vibrant);
        transform: translateY(-8px);
        box-shadow: 0 15px 35px rgba(255, 69, 0, 0.1);
    }
    .menu-item-card:active {
        transform: scale(0.95);
    }
    .item-icon {
        width: 60px;
        height: 60px;
        background-color: var(--primary-soft);
        color: var(--primary-vibrant);
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
        margin: 0 auto 1rem;
        transition: all 0.3s;
    }
    .menu-item-card:hover .item-icon {
        background-color: var(--primary-vibrant);
        color: white;
        transform: rotate(-10deg);
    }
    
    .cart-sticky {
        position: sticky;
        top: 100px;
        max-height: calc(100vh - 140px);
        display: flex;
        flex-direction: column;
        border-radius: 24px;
        border: 0;
        box-shadow: 0 10px 40px rgba(0,0,0,0.08);
    }
    
    .cart-items-container {
        overflow-y: auto;
        flex-grow: 1;
        padding-right: 5px;
    }

    .cart-item {
        background: white;
        border-radius: 12px;
        padding: 12px;
        margin-bottom: 10px;
        border: 1px solid var(--border-soft);
        transition: all 0.2s;
    }
    
    .cart-item:hover {
        border-color: var(--primary-vibrant);
    }

    .checkout-footer {
        background: #F8F9FA;
        margin: 0 -1.5rem -1.5rem;
        padding: 1.5rem;
        border-radius: 0 0 24px 24px;
        border-top: 1px solid var(--border-soft);
    }

    @media (max-width: 991.98px) {
        .pos-container { margin-bottom: 350px; }
        .cart-sticky {
            padding: 1.5rem;
            height: 320px;
            top: auto;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="pos-container animate-fade-in">
    <div class="row g-4">
        <!-- Menu Section -->
        <div class="col-lg-8">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 gap-3">
                <div>
                    <h2 class="section-title mb-1">Our Menu</h2>
                    <p class="text-secondary mb-0">Select items to start a new order</p>
                </div>
                <div class="input-group" style="max-width: 300px;">
                    <span class="input-group-text bg-white border-end-0"><i class="bi bi-search text-secondary"></i></span>
                    <input type="text" class="form-control border-start-0" placeholder="Search menu...">
                </div>
            </div>
            
            <div class="row g-3">
                {% for item in menu_items %}
                <div class="col-6 col-md-4">
                    <div class="card menu-item-card p-3 shadow-sm" onclick="addToCart({{ item.id }}, '{{ item.name }}', {{ item.price }})">
                        <div class="card-body text-center p-2">
                            <div class="item-icon">
                                <i class="bi bi-egg-fried"></i>
                            </div>
                            <h5 class="fw-bold mb-1 text-truncate">{{ item.name }}</h5>
                            <p class="text-vibrant fw-bold mb-0 fs-5">{{ item.price|floatformat:2 }} <small class="fw-normal small">EGP</small></p>
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="col-12 text-center py-5">
                    <div class="card border-0 bg-transparent">
                        <i class="bi bi-shop display-1 text-light"></i>
                        <h4 class="mt-3 text-secondary">No active menu items.</h4>
                        <p>Please add items in the admin panel.</p>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- Cart Section -->
        <div class="col-lg-4">
            <div class="card cart-sticky p-4 h-100">
                <div class="d-flex align-items-center mb-4">
                    <div class="bg-soft text-vibrant p-2 rounded-3 me-3">
                        <i class="bi bi-bag-check-fill fs-4"></i>
                    </div>
                    <h4 class="mb-0 fw-bold">Current Order</h4>
                </div>

                <div class="cart-items-container" id="cart-items-wrapper">
                    <div id="cart-items">
                        <div class="text-center py-5 text-secondary" id="empty-cart-msg">
                            <i class="bi bi-cart-x fs-1 opacity-25 d-block mb-3"></i>
                            Your cart is empty
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <label class="form-label small text-secondary fw-bold text-uppercase">Special Instructions</label>
                    <input type="text" id="customer-notes" class="form-control rounded-3 py-2 border-soft" placeholder="e.g. No onions, extra spicy">
                </div>

                <div class="checkout-footer mt-4">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-secondary fw-medium">Subtotal</span>
                        <span id="subtotal" class="fw-bold">0.00 EGP</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center pt-2 mb-4">
                        <h4 class="fw-bold mb-0">Total</h4>
                        <h3 class="fw-bold mb-0 text-vibrant" id="total">0.00 EGP</h3>
                    </div>

                    <button class="btn btn-vibrant w-100 py-3 fw-bold text-uppercase" onclick="completeOrder()" id="checkout-btn" disabled>
                        Place Order <i class="bi bi-arrow-right-short ms-1 fs-4"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-5 overflow-hidden">
            <div class="card border-0 w-100">
                <div class="card-body text-center py-5">
                    <div class="mb-4">
                        <div class="d-inline-flex bg-success bg-opacity-10 text-success p-4 rounded-circle">
                            <i class="bi bi-check2-circle display-1"></i>
                        </div>
                    </div>
                    <h2 class="fw-bold mb-2">Order Confirmed!</h2>
                    <p class="text-secondary mb-4 px-4" id="order-confirm-msg"></p>
                    <div class="d-grid gap-3 px-4">
                        <a id="print-receipt-btn" href="#" class="btn btn-vibrant py-3 fw-bold" target="_blank">
                            <i class="bi bi-printer me-2"></i> PRINT RECEIPT
                        </a>
                        <button type="button" class="btn btn-light py-2 rounded-3 text-secondary" onclick="location.reload()">NEW ORDER</button>
                    </div>
                </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 animate-fade-in';
            itemDiv.innerHTML = `
                <div class="flex-grow-1">
                    <div class="fw-bold text-dark">${item.name}</div>
                    <div class="small text-secondary">${item.price.toFixed(2)} x ${item.quantity}</div>
                </div>
                <div class="d-flex align-items-center gap-3">
                    <span class="fw-bold text-vibrant">${(item.price * item.quantity).toFixed(2)}</span>
                    <div class="btn-group btn-group-sm rounded-pill overflow-hidden border">
                        <button class="btn btn-light px-2" onclick="removeFromCart(${id})"><i class="bi bi-dash"></i></button>
                        <button class="btn btn-white px-2 disabled fw-bold">${item.quantity}</button>
                        <button class="btn btn-light px-2" onclick="addToCart(${id}, '${item.name}', ${item.price})"><i class="bi bi-plus"></i></button>
                    </div>
                </div>
            `;
            cartItemsDiv.appendChild(itemDiv);
        }

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

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

    function createEmptyMsg() {
        const div = document.createElement('div');
        div.id = 'empty-cart-msg';
        div.className = 'text-center py-5 text-secondary';
        div.innerHTML = '<i class="bi bi-cart-x fs-1 opacity-25 d-block mb-3"></i>Your cart is empty';
        return div;
    }

    async function completeOrder() {
        const btn = document.getElementById('checkout-btn');
        const notes = document.getElementById('customer-notes').value;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> 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.';
                document.getElementById('print-receipt-btn').href = '/receipt/' + result.order_number + '/';
                const modalElement = document.getElementById('successModal');
                const modal = new bootstrap.Modal(modalElement);
                modal.show();
            } else {
                alert('Error: ' + result.error);
                btn.disabled = false;
                btn.innerHTML = 'Place Order <i class="bi bi-arrow-right-short ms-1 fs-4"></i>';
            }
        } catch (error) {
            alert('Something went wrong. Please check stock levels.');
            btn.disabled = false;
            btn.innerHTML = 'Place Order <i class="bi bi-arrow-right-short ms-1 fs-4"></i>';
        }
    }
</script>
{% endblock %}