<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Cozinha - Siri Cascudo</title>
    <style>
        body { background: #333; color: white; font-family: sans-serif; padding: 20px; }
        .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
        .ticket { background: #fff; color: #000; padding: 15px; border-radius: 5px; }
        .ticket.preparing { background: #fffacd; border: 3px solid #ffd700; }
        .header { display: flex; justify-content: space-between; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 10px; }
        .items { list-style: none; padding: 0; }
        .items li { border-bottom: 1px dashed #ccc; padding: 5px 0; font-size: 1.2rem; }
        .actions { margin-top: 15px; display: flex; gap: 10px; }
        button { flex: 1; padding: 10px; cursor: pointer; font-weight: bold; }
        .btn-prep { background: #FFA500; color: white; border: none; }
        .btn-done { background: #28a745; color: white; border: none; }
        
        /* POS Modal Styles */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; }
        .modal.active { display: flex; justify-content: center; align-items: center; }
        .modal-content { background: #fff; color: #333; padding: 20px; border-radius: 8px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto; }
        .pos-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .pos-products { border-right: 1px solid #ddd; padding-right: 20px; }
        .pos-summary { padding-left: 20px; }
        .pos-item-list { list-style: none; padding: 0; margin: 10px 0; max-height: 200px; overflow-y: auto; }
        .pos-item-list li { display: flex; justify-content: space-between; padding: 5px 0; border-bottom: 1px solid #eee; }
        .btn-pos { background: #007bff; color: white; border: none; padding: 4px 8px; font-size: 0.8rem; border-radius: 4px; margin-bottom: 10px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
        .form-group input, .form-group select { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
    </style>
</head>
<body>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h1>KDS - Cozinha (Pedidos em Tempo Real)</h1>
        <button onclick="openPos()" class="btn-pos">🍔 Novo Pedido (Balcão)</button>
    </div>

    <div id="orders-grid" class="grid">
        <!-- Pedidos via JS -->
    </div>

    <audio id="alert-sound" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3" loop></audio>

    <!-- POS Modal -->
    <div id="pos-modal" class="modal">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
                <h2>Novo Pedido Avulso</h2>
                <button onclick="closePos()" style="background: none; color: #333; border: none; font-size: 1.5rem; width: auto; flex: none;">&times;</button>
            </div>
            
            <div class="pos-grid">
                <div class="pos-products">
                    <div class="form-group">
                        <label>Produto</label>
                        <select id="pos-product-select" onchange="addToPosList()">
                            <option value="">Selecione...</option>
                            <!-- Populated via JS -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Quantidade</label>
                        <input type="number" id="pos-qty" value="1" min="1">
                    </div>
                    <div class="form-group">
                        <label>Observação</label>
                        <input type="text" id="pos-note" placeholder="Ex: Sem cebola">
                    </div>
                    <button onclick="addToPosList()" style="background: #28a745; color: white; width: 100%;">Adicionar Item</button>
                </div>
                
                <div class="pos-summary">
                    <h3>Resumo</h3>
                    <ul id="pos-items" class="pos-item-list"></ul>
                    <div style="font-size: 1.2rem; font-weight: bold; margin: 10px 0; text-align: right;">
                        Total: R$ <span id="pos-total">0,00</span>
                    </div>
                    
                    <hr>
                    
                    <div class="form-group">
                        <label>Nome do Cliente (Para chamar)</label>
                        <input type="text" id="pos-customer" placeholder="Nome">
                    </div>
                    
                    <div class="form-group">
                        <label>Forma de Pagamento</label>
                        <select id="pos-payment">
                            <option value="dinheiro">Dinheiro</option>
                            <option value="pix">Pix</option>
                            <option value="cartao">Cartão</option>
                        </select>
                    </div>
                    
                    <button onclick="confirmPosOrder()" style="background: #007bff; color: white; width: 100%; font-size: 1.2rem;">Confirmar Pedido</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let posItems = [];
        let products = [];
        let audioPlaying = false;
        const audio = document.getElementById('alert-sound');

        // Load products for POS
        fetch('/api/cozinha/produtos')
            .then(r => r.json())
            .then(data => {
                products = data;
                const select = document.getElementById('pos-product-select');
                products.forEach(p => {
                    const opt = document.createElement('option');
                    opt.value = p.id;
                    opt.textContent = `${p.name} - R$ ${parseFloat(p.base_price).toFixed(2)}`;
                    opt.dataset.price = p.base_price;
                    opt.dataset.name = p.name;
                    select.appendChild(opt);
                });
            });

        function loadOrders() {
            fetch('/api/cozinha/pedidos')
                .then(r => r.json())
                .then(orders => {
                    const grid = document.getElementById('orders-grid');
                    grid.innerHTML = '';
                    
                    if (orders.length === 0) {
                        grid.innerHTML = '<p>Nenhum pedido pendente.</p>';
                        stopAudio();
                        return;
                    }

                    let hasPending = false;

                    orders.forEach(order => {
                        if (order.status === 'pending') hasPending = true;

                        const div = document.createElement('div');
                        div.className = 'ticket ' + order.status;
                        
                        let itemsHtml = '';
                        order.items.forEach(item => {
                            itemsHtml += `<li>${item.quantity}x ${item.product_name} <br><small>${item.notes || ''}</small></li>`;
                        });

                        div.innerHTML = `
                            <div class="header">
                                <strong>#${order.id} - ${order.customer_name}</strong>
                                <span>${new Date(order.created_at).toLocaleTimeString()}</span>
                            </div>
                            <ul class="items">${itemsHtml}</ul>
                            <div class="actions">
                                ${order.status === 'pending' ? 
                                    `<button class="btn-prep" onclick="updateStatus(${order.id}, 'preparing')">👨‍🍳 Preparar</button>` : 
                                    `<button class="btn-done" onclick="updateStatus(${order.id}, 'ready')">✅ Pronto</button>`
                                }
                            </div>
                        `;
                        grid.appendChild(div);
                    });

                    if (hasPending) {
                        playAudio();
                    } else {
                        stopAudio();
                    }
                });
        }

        function playAudio() {
            if (!audioPlaying) {
                audio.play().catch(e => console.log('Autoplay blocked:', e));
                audioPlaying = true;
            }
        }

        function stopAudio() {
            if (audioPlaying) {
                audio.pause();
                audio.currentTime = 0;
                audioPlaying = false;
            }
        }

        function updateStatus(id, status) {
            const formData = new FormData();
            formData.append('id', id);
            formData.append('status', status);

            fetch('/api/cozinha/status', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(() => {
                loadOrders();
                if (status === 'preparing') {
                    window.open('/rastreio/' + id + '?print=1', '_blank', 'width=800,height=600');
                }
            });
        }

        // POS Functions
        function openPos() {
            document.getElementById('pos-modal').classList.add('active');
        }

        function closePos() {
            document.getElementById('pos-modal').classList.remove('active');
            posItems = [];
            updatePosList();
        }

        function addToPosList() {
            const select = document.getElementById('pos-product-select');
            const qtyInput = document.getElementById('pos-qty');
            const noteInput = document.getElementById('pos-note');
            
            if (!select.value) return;

            const option = select.options[select.selectedIndex];
            const price = parseFloat(option.dataset.price);
            const qty = parseInt(qtyInput.value);
            const total = price * qty;

            posItems.push({
                id: option.value,
                name: option.dataset.name,
                price: price,
                quantity: qty,
                total: total,
                notes: noteInput.value
            });

            qtyInput.value = 1;
            noteInput.value = '';
            select.value = '';
            updatePosList();
        }

        function updatePosList() {
            const list = document.getElementById('pos-items');
            const totalSpan = document.getElementById('pos-total');
            list.innerHTML = '';
            
            let total = 0;
            posItems.forEach((item, index) => {
                total += item.total;
                const li = document.createElement('li');
                li.innerHTML = `
                    <span>${item.quantity}x ${item.name} <small>(${item.notes})</small></span>
                    <span>R$ ${item.total.toFixed(2)} <button onclick="removePosItem(${index})" style="background:red; color:white; border:none; padding:2px 5px; margin-left:5px; cursor:pointer;">&times;</button></span>
                `;
                list.appendChild(li);
            });

            totalSpan.textContent = total.toFixed(2).replace('.', ',');
        }

        function removePosItem(index) {
            posItems.splice(index, 1);
            updatePosList();
        }

        function confirmPosOrder() {
            const customer = document.getElementById('pos-customer').value;
            const payment = document.getElementById('pos-payment').value;
            
            if (posItems.length === 0) {
                alert('Adicione itens ao pedido.');
                return;
            }
            if (!customer) {
                alert('Informe o nome do cliente.');
                return;
            }

            if (!confirm(`Confirmar pedido para ${customer}? Total: R$ ${document.getElementById('pos-total').textContent}`)) {
                return;
            }

            let totalVal = 0;
            posItems.forEach(i => totalVal += i.total);

            fetch('/api/cozinha/pedido', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    customer_name: customer,
                    payment_method: payment,
                    items: posItems,
                    total: totalVal
                })
            })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    alert('Pedido criado!');
                    closePos();
                    loadOrders();
                } else {
                    alert('Erro: ' + res.message);
                }
            });
        }

        // Auto load every 5 seconds
        setInterval(loadOrders, 5000);
        loadOrders();
    </script>
</body>
</html>
