<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title>Sabor da Terra - MotoDelivery</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; padding: 16px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; padding: 24px; border-radius: 20px; text-align: center; margin-bottom: 20px; }
        .header h1 { font-size: 28px; }
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .card { background: white; border-radius: 20px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .card h2 { border-bottom: 2px solid #25D366; padding-bottom: 10px; margin-bottom: 15px; }
        .cardapio-item { background: #f8f9fa; padding: 14px; border-radius: 14px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; }
        .item-nome { font-weight: 600; }
        .item-preco { font-weight: 700; color: #25D366; font-size: 18px; }
        .btn-add { background: #25D366; color: white; border: none; width: 36px; height: 36px; border-radius: 10px; font-size: 20px; cursor: pointer; transition: transform 0.2s; }
        .btn-add:hover { transform: scale(1.05); }
        .carrinho-item { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #eee; }
        .btn-qtd { background: #f0f0f0; border: none; width: 28px; height: 28px; border-radius: 6px; cursor: pointer; margin: 0 2px; }
        .btn-remove { background: #dc3545; color: white; border: none; width: 28px; height: 28px; border-radius: 6px; cursor: pointer; }
        .resumo-pedido { background: #f8f9fa; padding: 16px; border-radius: 14px; margin-top: 16px; }
        .resumo-total { font-weight: bold; font-size: 18px; color: #25D366; text-align: right; margin-top: 10px; padding-top: 10px; border-top: 1px solid #ddd; }
        input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 12px; margin-bottom: 10px; font-size: 14px; }
        .btn-finalizar { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; border: none; padding: 14px; border-radius: 14px; font-weight: bold; font-size: 16px; cursor: pointer; width: 100%; margin-top: 16px; transition: opacity 0.2s; }
        .btn-finalizar:hover { opacity: 0.9; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center; }
        .modal-content { background: white; border-radius: 24px; max-width: 400px; width: 90%; padding: 24px; text-align: center; max-height: 90vh; overflow-y: auto; }
        .opcao-pagamento { background: #f8f9fa; padding: 16px; border-radius: 14px; cursor: pointer; margin-bottom: 12px; border: 2px solid transparent; transition: all 0.2s; }
        .opcao-pagamento.selected { border-color: #25D366; background: #d4edda; }
        .qrcode-img img { max-width: 200px; margin: 15px 0; border-radius: 12px; }
        .btn-pagamento { background: #25D366; color: white; border: none; padding: 12px; border-radius: 12px; font-weight: bold; cursor: pointer; width: 100%; margin-top: 15px; }
        .btn-fechar { background: #6c757d; color: white; border: none; padding: 12px; border-radius: 12px; cursor: pointer; width: 100%; margin-top: 10px; }
        @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🍔 Sabor da Terra</h1>
        <p>Peça online e receba em casa</p>
    </div>

    <div class="grid">
        <div class="card">
            <h2>🍕 Cardápio</h2>
            <div id="cardapio">Carregando...</div>
        </div>

        <div class="card">
            <h2>🛒 Seu Pedido</h2>
            <div id="carrinho"></div>
            <div id="resumo" class="resumo-pedido" style="display: none;">
                <div style="display: flex; justify-content: space-between;">
                    <span>Subtotal:</span>
                    <span id="subtotal">R$ 0,00</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin-top: 5px;">
                    <span>Taxa de entrega:</span>
                    <span>R$ 7,00</span>
                </div>
                <div class="resumo-total">
                    <span>TOTAL:</span>
                    <span id="total">R$ 0,00</span>
                </div>
            </div>
            <input type="text" id="cliente_nome" placeholder="👤 Seu nome completo">
            <input type="text" id="cliente_endereco" placeholder="📍 Seu endereço completo">
            <input type="tel" id="cliente_whatsapp" placeholder="📱 WhatsApp (11999999999)">
            <button class="btn-finalizar" onclick="abrirModalPagamento()">✅ Finalizar Pedido</button>
        </div>
    </div>
</div>

<div id="modalPagamento" class="modal">
    <div class="modal-content">
        <h3>💰 Escolha a forma de pagamento</h3>
        <div class="opcao-pagamento" data-tipo="dinheiro" onclick="selecionarPagamento('dinheiro', this)">
            💵 <strong>Dinheiro na entrega</strong><br>
            <small>Pague ao entregador no momento da entrega</small>
        </div>
                <div class="opcao-pagamento" data-tipo="pix" onclick="selecionarPagamento('pix', this)">
            📱 <strong>PIX (QR Code)</strong><br>
            <small>Pague com QR Code do seu banco</small>
        </div>
                        <div id="detalhesPagamento" style="margin-top: 15px;"></div>
        <button class="btn-fechar" onclick="fecharModal()">Fechar</button>
    </div>
</div>

<script>
    let carrinho = [];
    let restauranteId = 22;
    let pagamentoSelecionado = null;
    let qrCodeUrl = "https:\/\/mvp.criarpro.com.br\/uploads\/qrcodes\/1777730642_69f604523b066.png";
    let linkMercadoPago = null;

    async function carregarCardapio() {
        try {
            const resp = await fetch(`api/cardapio.php?restaurante_id=${restauranteId}`);
            const dados = await resp.json();
            const produtos = dados.cardapio || dados;
            if (!Array.isArray(produtos) || produtos.length === 0) {
                document.getElementById('cardapio').innerHTML = '<p>Nenhum item no cardápio</p>';
                return;
            }
            let html = '';
            for (let p of produtos) {
                html += `
                    <div class="cardapio-item">
                        <div>
                            <div class="item-nome">${escapeHtml(p.nome)}</div>
                            <small>${escapeHtml(p.descricao || '')}</small>
                        </div>
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <span class="item-preco">R$ ${parseFloat(p.preco).toFixed(2)}</span>
                            <button class="btn-add" onclick="adicionar(${p.id}, '${escapeHtml(p.nome)}', ${parseFloat(p.preco)})">+</button>
                        </div>
                    </div>
                `;
            }
            document.getElementById('cardapio').innerHTML = html;
        } catch(e) {
            console.error('Erro ao carregar cardápio:', e);
            document.getElementById('cardapio').innerHTML = '<p>Erro ao carregar cardápio</p>';
        }
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function adicionar(id, nome, preco) {
        let existente = carrinho.find(i => i.id === id);
        if (existente) {
            existente.qtd++;
        } else {
            carrinho.push({ id, nome, preco: parseFloat(preco), qtd: 1 });
        }
        renderizarCarrinho();
    }

    function alterarQtd(id, delta) {
        let idx = carrinho.findIndex(i => i.id === id);
        if (idx !== -1) {
            let novaQtd = carrinho[idx].qtd + delta;
            if (novaQtd <= 0) {
                carrinho.splice(idx, 1);
            } else {
                carrinho[idx].qtd = novaQtd;
            }
            renderizarCarrinho();
        }
    }

    function remover(id) {
        carrinho = carrinho.filter(i => i.id !== id);
        renderizarCarrinho();
    }

    function renderizarCarrinho() {
        const carrinhoDiv = document.getElementById('carrinho');
        const resumoDiv = document.getElementById('resumo');
        
        if (carrinho.length === 0) {
            carrinhoDiv.innerHTML = '<div style="text-align:center; padding:40px; color:#aaa;">🛒 Carrinho vazio</div>';
            resumoDiv.style.display = 'none';
            return;
        }

        let subtotal = 0;
        let html = '';
        for (let item of carrinho) {
            let totalItem = item.preco * item.qtd;
            subtotal += totalItem;
            html += `
                <div class="carrinho-item">
                    <div>
                        <strong>${escapeHtml(item.nome)}</strong><br>
                        ${item.qtd}x R$ ${item.preco.toFixed(2)}
                    </div>
                    <div>
                        R$ ${totalItem.toFixed(2)}
                        <div style="margin-top: 5px;">
                            <button class="btn-qtd" onclick="alterarQtd(${item.id}, -1)">-</button>
                            <button class="btn-qtd" onclick="alterarQtd(${item.id}, 1)">+</button>
                            <button class="btn-remove" onclick="remover(${item.id})">✕</button>
                        </div>
                    </div>
                </div>
            `;
        }

        let total = subtotal + 7.00;
        carrinhoDiv.innerHTML = html;
        resumoDiv.style.display = 'block';
        document.getElementById('subtotal').innerHTML = `R$ ${subtotal.toFixed(2)}`;
        document.getElementById('total').innerHTML = `R$ ${total.toFixed(2)}`;
    }

    function abrirModalPagamento() {
        if (carrinho.length === 0) {
            alert('Adicione itens ao carrinho');
            return;
        }
        const nome = document.getElementById('cliente_nome').value.trim();
        const endereco = document.getElementById('cliente_endereco').value.trim();
        const whatsapp = document.getElementById('cliente_whatsapp').value.trim();
        if (!nome || !endereco || !whatsapp) {
            alert('Preencha nome, endereço e WhatsApp');
            return;
        }
        if (whatsapp.replace(/\D/g, '').length < 10) {
            alert('WhatsApp inválido. Digite um número válido (DDD + número)');
            return;
        }
        document.getElementById('modalPagamento').style.display = 'flex';
        document.getElementById('detalhesPagamento').innerHTML = '';
        pagamentoSelecionado = null;
        document.querySelectorAll('.opcao-pagamento').forEach(el => el.classList.remove('selected'));
    }

    function selecionarPagamento(tipo, elemento) {
        pagamentoSelecionado = tipo;
        document.querySelectorAll('.opcao-pagamento').forEach(el => el.classList.remove('selected'));
        elemento.classList.add('selected');
        
        const detalhesDiv = document.getElementById('detalhesPagamento');
        const subtotal = carrinho.reduce((s, i) => s + (i.preco * i.qtd), 0);
        const total = subtotal + 7.00;

        if (tipo === 'dinheiro') {
            detalhesDiv.innerHTML = `
                <div style="background:#e8f5e9; padding:15px; border-radius:12px;">
                    <strong>💵 Pagamento em dinheiro</strong><br>
                    Valor: R$ ${total.toFixed(2)}<br>
                    <button class="btn-pagamento" onclick="finalizarPedido()">✅ Confirmar pedido</button>
                </div>`;
        } else if (tipo === 'pix' && qrCodeUrl) {
            detalhesDiv.innerHTML = `
                <div style="background:#e8f5e9; padding:15px; border-radius:12px;">
                    <strong>📱 Pagamento via PIX</strong>
                    <div class="qrcode-img"><img src="${qrCodeUrl}" alt="QR Code PIX" style="max-width:100%;"></div>
                    Valor: R$ ${total.toFixed(2)}<br>
                    <button class="btn-pagamento" onclick="finalizarPedido()">✅ Já paguei</button>
                </div>`;
        } else if (tipo === 'mercado_pago' && linkMercadoPago) {
            detalhesDiv.innerHTML = `
                <div style="background:#e8f5e9; padding:15px; border-radius:12px;">
                    <strong>🔗 Pagamento via Mercado Pago</strong><br>
                    <a href="${linkMercadoPago}" target="_blank" rel="noopener noreferrer">Clique aqui para pagar</a><br>
                    Valor: R$ ${total.toFixed(2)}<br>
                    <button class="btn-pagamento" onclick="finalizarPedido()">✅ Confirmar pedido</button>
                </div>`;
        }
    }

    function fecharModal() {
        document.getElementById('modalPagamento').style.display = 'none';
        pagamentoSelecionado = null;
    }

    async function finalizarPedido() {
        if (!pagamentoSelecionado) {
            alert('Selecione uma forma de pagamento');
            return;
        }

        const nome = document.getElementById('cliente_nome').value.trim();
        const endereco = document.getElementById('cliente_endereco').value.trim();
        const whatsapp = document.getElementById('cliente_whatsapp').value.trim();
        const subtotal = carrinho.reduce((s, i) => s + (i.preco * i.qtd), 0);
        
        const pedido = {
            restaurante_id: restauranteId,
            cliente_nome: nome,
            cliente_endereco: endereco,
            cliente_whatsapp: whatsapp.replace(/\D/g, ''),
            forma_pagamento: pagamentoSelecionado,
            subtotal: subtotal,
            itens: carrinho.map(i => ({ 
                id: i.id,
                nome: i.nome, 
                quantidade: i.qtd, 
                preco: i.preco 
            }))
        };

        fecharModal();

        try {
            const resp = await fetch('api/pedido.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(pedido)
            });
            const resultado = await resp.json();
            if (resultado.sucesso) {
                alert(`✅ Pedido #${resultado.pedido_id} confirmado!`);
                carrinho = [];
                renderizarCarrinho();
                document.getElementById('cliente_nome').value = '';
                document.getElementById('cliente_endereco').value = '';
                document.getElementById('cliente_whatsapp').value = '';
            } else {
                alert('❌ Erro: ' + (resultado.erro || 'Tente novamente'));
            }
        } catch(error) {
            console.error('Erro ao finalizar pedido:', error);
            alert('❌ Erro de conexão. Tente novamente.');
        }
    }

    // Fechar modal ao clicar fora
    window.onclick = function(event) {
        const modal = document.getElementById('modalPagamento');
        if (event.target === modal) {
            fecharModal();
        }
    }

    carregarCardapio();
</script>
</body>
</html>