<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Meu Mec - PDV (Edição de Fechamento)</title>
    <style>
        body { background-color: #d4d0c8; font-family: 'Tahoma', sans-serif; font-size: 11px; margin: 0; padding: 10px; overflow: hidden; }
        .win-panel { border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; padding: 8px; background: #d4d0c8; }
        .display-total { background: #000; color: #0f0; font-family: 'Courier New'; font-size: 56px; text-align: right; padding: 10px; border: 3px inset #808080; margin-bottom: 10px; }
        .area-tabela { height: 280px; overflow-y: scroll; background: white; border: 2px inset #808080; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #0a246a; color: white; padding: 5px; position: sticky; top: 0; text-align: left; font-weight: normal; }
        td { padding: 6px; border-bottom: 1px solid #d4d0c8; font-size: 13px; }
        input, select { border: 2px inset #ffffff; padding: 5px; font-weight: bold; font-family: 'Tahoma'; }
        .btn-win { border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; padding: 5px 15px; background: #d4d0c8; cursor: pointer; }
        .btn-win:active { border-color: #808080 #ffffff #ffffff #808080; }
        .modal { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000; box-shadow: 4px 4px 10px rgba(0,0,0,0.5); }
        .modal-header { background: #0a246a; color: white; padding: 4px 10px; font-weight: bold; display: flex; justify-content: space-between; }
        fieldset { border: 2px groove #fff; padding: 10px; margin-bottom: 10px; }
        .label-fatura { display: block; margin-bottom: 2px; font-weight: bold; }
    </style>
</head>
<body>

<div style="display: flex; gap: 10px;">
    <div style="flex: 3;">
        <div class="display-total" id="visor_total">R$ 0,00</div>
        <div class="area-tabela">
            <table id="tabela_venda">
                <thead>
                    <tr><th>Item</th><th>Código</th><th>Descrição</th><th>Qtd</th><th>Unit</th><th>Total</th></tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <div class="win-panel" style="margin-top: 10px;">
            <label><strong>ENTRADA DE PRODUTO (F2)</strong></label><br>
            <input type="text" id="input_barras" style="width: 100%; font-size: 24px; color: #000080;" autofocus autocomplete="off">
        </div>
    </div>
    <div style="flex: 1;">
        <div class="win-panel" style="height: 100%;">
            <h4>COMANDOS</h4>
            <p><b>[F2]</b> Focar Entrada</p>
            <p><b>[F5]</b> Finalizar Venda</p>
            <p><b>[ESC]</b> Sair / Cancelar</p>
            <hr>
            <p>Operador: <b>Fabiano</b></p>
        </div>
    </div>
</div>

<div id="modal_pesquisa" class="modal win-panel" style="width: 700px;">
    <div class="modal-header">
        <span>PESQUISA NA TABELA REG_0200</span>
        <span onclick="fechar('modal_pesquisa')" style="cursor:pointer;">[X]</span>
    </div>
    <div style="padding: 10px;">
        <fieldset>
            <legend>Filtros</legend>
            <div style="display: flex; gap: 10px;">
                <input type="text" id="f_manual_cod" placeholder="Código" onkeypress="if(event.key=='Enter') buscarManual()">
                <input type="text" id="f_manual_desc" placeholder="Descrição" style="flex:1" onkeypress="if(event.key=='Enter') buscarManual()">
                <button class="btn-win" onclick="buscarManual()">FILTRAR</button>
            </div>
        </fieldset>
        <div style="height: 200px; background: white; border: 2px inset #808080; overflow-y: scroll;">
            <table id="res_busca">
                <thead style="background: #ccc;">
                    <tr><th>Cód</th><th>Descrição</th><th>Preço</th><th>Saldo</th><th>Ação</th></tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>

<div id="modal_fechar" class="modal win-panel" style="width: 480px;">
    <div class="modal-header">FECHAMENTO DA VENDA</div>
    <div style="padding: 15px;">
        <div style="display: flex; gap: 10px; margin-bottom: 10px;">
            <div style="flex: 1;">
                <label class="label-fatura">TOTAL BRUTO:</label>
                <input type="text" id="f_bruto" readonly style="width: 100%; background: #eee; text-align: right; border: 2px inset #fff;">
            </div>
            <div style="flex: 1;">
                <label class="label-fatura" style="color: blue;">DESCONTO (R$):</label>
                <input type="number" id="f_desc" step="0.01" style="width: 100%; text-align: right; color: blue;" oninput="calcFatura()" value="0.00">
            </div>
        </div>

        <label class="label-fatura">TOTAL LÍQUIDO A PAGAR:</label>
        <input type="text" id="f_liquido" readonly style="width: 100%; font-size: 24px; background: #ffffcc; text-align: right; border: 2px inset #808080; margin-bottom: 10px;">

        <fieldset>
            <legend>Dados do Cliente</legend>
            <label class="label-fatura">CPF / CNPJ:</label>
            <input type="text" id="f_doc" style="width: 100%; margin-bottom: 5px;" placeholder="Digite para identificar...">
            <select id="f_cliente" style="width: 100%;"><option value="0">CONSUMIDOR GERAL</option></select>
        </fieldset>

        <div style="display: flex; gap: 10px; margin-bottom: 15px;">
            <div style="flex: 1;">
                <label class="label-fatura">VALOR À VISTA:</label>
                <input type="number" id="f_vista" step="0.01" style="width: 100%; color: green; font-size: 16px;" oninput="calcSaldo()">
            </div>
            <div style="flex: 1;">
                <label class="label-fatura">SALDO NO TÍTULO:</label>
                <input type="text" id="f_saldo" readonly style="width: 100%; color: red; background: #eee; font-size: 16px;">
            </div>
        </div>

        <div style="text-align: right; border-top: 1px solid #808080; padding-top: 10px;">
            <button class="btn-win" onclick="executarGravacao()" style="font-weight: bold;">GRAVAR (F5)</button>
            <button class="btn-win" onclick="fechar('modal_fechar')">VOLTAR</button>
        </div>
    </div>
</div>

<script>
    let totalVenda = 0;
    let itensVenda = [];

    // Atalhos de Teclado
    document.addEventListener('keydown', e => {
        if(e.key === 'F2') { e.preventDefault(); document.getElementById('input_barras').focus(); }
        if(e.key === 'F5') {
            e.preventDefault();
            if(document.getElementById('modal_fechar').style.display === 'block') {
                executarGravacao();
            } else if(totalVenda > 0) {
                abrirFechamento();
            }
        }
        if(e.key === 'Escape') { fechar('modal_pesquisa'); fechar('modal_fechar'); }
    });

    document.getElementById('input_barras').addEventListener('keypress', e => {
        if(e.key === 'Enter') {
            let b = e.target.value;
            if(!b) return;
            fetch(`buscar_item.php?tipo=barras&barras=${b}`)
                .then(r => r.json())
                .then(d => {
                    if(d.length > 0) {
                        addItem(d[0].reg_0200_cod_item, d[0].reg_0200_descr_item, d[0].reg_0200_preco, 1);
                        e.target.value = '';
                    } else { abrirPesquisa(b); }
                });
        }
    });

    function addItem(c, d, p, q) {
        let subtotal = parseFloat(p) * q;
        totalVenda += subtotal;
        itensVenda.push({cod: c, desc: d, unit: p, qtd: q});
        
        let tb = document.querySelector('#tabela_venda tbody');
        let row = tb.insertRow(0);
        row.innerHTML = `<td>${tb.rows.length}</td><td>${c}</td><td>${d}</td><td>${q}</td><td>${parseFloat(p).toFixed(2)}</td><td>${subtotal.toFixed(2)}</td>`;
        document.getElementById('visor_total').innerText = totalVenda.toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
        document.getElementById('input_barras').value = '';
        document.getElementById('input_barras').focus();
    }

    function abrirFechamento() {
        document.getElementById('modal_fechar').style.display = 'block';
        document.getElementById('f_bruto').value = totalVenda.toFixed(2);
        document.getElementById('f_desc').value = "0.00";
        calcFatura();
        setTimeout(() => document.getElementById('f_desc').focus(), 100);
    }

    function calcFatura() {
        let bruto = totalVenda;
        let desc = parseFloat(document.getElementById('f_desc').value) || 0;
        let liquido = bruto - desc;
        document.getElementById('f_liquido').value = liquido.toFixed(2);
        document.getElementById('f_vista').value = liquido.toFixed(2);
        calcSaldo();
    }

    function calcSaldo() {
        let liq = parseFloat(document.getElementById('f_liquido').value);
        let vis = parseFloat(document.getElementById('f_vista').value) || 0;
        document.getElementById('f_saldo').value = (liq - vis).toFixed(2);
    }

    function executarGravacao() {
        const dadosVenda = {
            doc: document.getElementById('f_doc').value,
            bruto: totalVenda,
            desconto: document.getElementById('f_desc').value,
            pago_vista: document.getElementById('f_vista').value,
            saldo_titulo: document.getElementById('f_saldo').value,
            itens: itensVenda
        };

        alert("Venda enviada para processamento!\nBruto: R$ " + dadosVenda.bruto + "\nLíquido: R$ " + document.getElementById('f_liquido').value);
        
        // Aqui você faria o fetch para um arquivo 'salvar_venda.php'
        console.log("JSON da Venda:", dadosVenda);
        
        location.reload(); // Só recarrega após a sua lógica de confirmação
    }

    function abrirPesquisa(t) {
        document.getElementById('modal_pesquisa').style.display = 'block';
        document.getElementById('f_manual_desc').value = t;
        buscarManual();
    }

    function buscarManual() {
        let c = document.getElementById('f_manual_cod').value;
        let d = document.getElementById('f_manual_desc').value;
        let tb = document.querySelector('#res_busca tbody');
        fetch(`buscar_item.php?tipo=manual&cod=${c}&desc=${d}`)
            .then(r => r.json())
            .then(dados => {
                tb.innerHTML = dados.map(i => `
                    <tr>
                        <td>${i.reg_0200_cod_item}</td><td>${i.reg_0200_descr_item}</td><td>${i.reg_0200_preco}</td>
                        <td style="color:${i.saldo<=0?'red':'blue'}">${i.saldo}</td>
                        <td><button class="btn-win" onclick="pedirQtd('${i.reg_0200_cod_item}','${i.reg_0200_descr_item}',${i.reg_0200_preco})">OK</button></td>
                    </tr>
                `).join('');
            });
    }

    function pedirQtd(c, d, p) {
        let q = prompt("Quantidade para " + d, "1");
        if(q) { addItem(c, d, p, parseFloat(q)); fechar('modal_pesquisa'); }
    }

    function fechar(id) { document.getElementById(id).style.display = 'none'; document.getElementById('input_barras').focus(); }
</script>
</body>
</html>