<?php
session_start();
if (!isset($_SESSION['id'])) { header("Location: ../index/index.php"); exit(); }

include '../config.php';
include '../configuracao/modelo.php';

if (!isset($mysqli) || $mysqli->connect_error) {
    die("Erro de conexão.");
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>NF - Gestão de Impostos por Item</title>
    <style>
        * { box-sizing: border-box; }
        html, body { height: 100%; margin: 0; padding: 0; background-color: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; overflow: hidden; }
        .desktop-wrapper { display: flex; flex-direction: column; height: 100vh; padding: 4px; }
        .window { display: flex; flex-direction: column; flex: 1; border: 2px solid; border-color: #ffffff #808080 #808080 #ffffff; background: #c0c0c0; box-shadow: 1px 1px 0px #000; overflow: hidden; }
        .title-bar { background: linear-gradient(90deg, #000080, #1084d0); color: white; padding: 3px 6px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
        
        .content { padding: 8px; flex: 1; display: flex; flex-direction: column; gap: 8px; overflow: hidden; }
        
        fieldset { border: 2px inset #fff; padding: 10px; margin: 0; flex-shrink: 0; }
        legend { font-weight: bold; padding: 0 5px; }
        
        #itens-fieldset { flex: 1; display: flex; flex-direction: column; min-height: 0; }
        
        .form-grid { display: grid; grid-template-columns: 100px 150px 1fr 140px 60px; gap: 8px; }
        .field-group { display: flex; flex-direction: column; }
        label { margin-bottom: 2px; font-weight: bold; }
        input, select { padding: 3px; border: 2px inset #fff; background: #fff; font-family: "Tahoma", sans-serif; font-size: 11px; height: 22px; }
        input[readonly] { background: #d4d0c8; color: #404040; cursor: not-allowed; }
        
        .search-group { display: flex; align-items: center; }
        .btn-search { width: 22px; height: 22px; background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; margin: 0 1px; }
        
        .table-container { flex: 1; background: #fff; border: 2px solid; border-color: #808080 #fff #fff #808080; overflow-y: scroll; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 1000px; }
        
        th { border: 1px solid #808080; padding: 6px; background: #d4d0c8; position: sticky; top: 0; font-size: 10px; text-transform: uppercase; z-index: 10; box-shadow: inset 0 -1px 0 #808080; }
        td { border: 1px solid #f0f0f0; padding: 2px; }

        .tabs-grid-footer { background: #c0c0c0; border: 1px solid #808080; flex-shrink: 0; margin-top: 5px; }
        .tabs-header { display: flex; border-bottom: 1px solid #808080; background: #d4d0c8; padding: 2px 2px 0 2px; overflow-x: auto; }
        .tab-btn { padding: 4px 12px; cursor: pointer; border: 1px solid #808080; border-bottom: none; background: #b0b0b0; font-weight: bold; margin-right: 2px; white-space: nowrap; }
        .tab-btn.active { background: #c0c0c0; border-top: 2px solid #fff; border-left: 2px solid #fff; margin-bottom: -1px; }
        .tab-content { display: none; padding: 5px; background: #c0c0c0; border: 2px inset #fff; }
        .tab-content.active { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 5px; }
        .total-box { border: 1px dotted #808080; padding: 2px 5px; font-size: 10px; }
        .total-box span { color: #000080; font-weight: bold; display: block; }
        .total-box label { font-size: 9px; display: block; color: #404040; }

        .footer-bar { display: flex; justify-content: flex-end; gap: 10px; padding: 5px 0; flex-shrink: 0; }
        .btn-main { padding: 6px 20px; background: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff; font-weight: bold; cursor: pointer; }
        .btn-tax { background: #e1e1e1; font-size: 9px; cursor: pointer; border: 1px solid #808080; }

        #modalImpostos { display: none; position: fixed; z-index: 100; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.4); }
        .modal-content { background-color: #c0c0c0; margin: 5% auto; padding: 2px; border: 2px solid #fff; width: 600px; box-shadow: 2px 2px 10px #000; }
        .tax-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; padding: 10px; }
        .tax-section { border: 1px inset #fff; padding: 8px; margin-bottom: 5px; }
        .tax-section h4 { margin: 0 0 5px 0; color: #000080; font-size: 10px; }

        .status-bar { display: flex; padding: 2px; background: #c0c0c0; border-top: 1px solid #808080; height: 28px; flex-shrink: 0; }
        .status-panel { border: 1px inset #fff; padding: 2px 8px; flex: 1; display: flex; justify-content: space-between; align-items: center; }
    </style>
</head>

<body>
<div class="desktop-wrapper">
    <div class="window">
        <div class="title-bar">
            <span>NF - Gestão de Notas Fiscais Profissional</span>
            <div style="display:flex; gap: 2px;">
                <button type="button" style="width:16px; height:14px; font-size:9px; background:#c0c0c0; border:1px solid #000;">_</button>
                <button type="button" style="width:16px; height:14px; font-size:9px; background:#c0c0c0; border:1px solid #000;" onclick="location.reload()">X</button>
            </div>
        </div>

        <form id="orcForm" action="processar_nf.php" method="POST" class="content">
            <fieldset>
                <legend>Cabeçalho do NF</legend>
                <div class="form-grid">
                    <div class="field-group"><label>Nº ID:</label><input type="text" name="codigo" id="val_codigo" readonly placeholder="NOVO"></div>
                    <div class="field-group">
                        <label>Cód. Participante:</label>
                        <div class="search-group">
                            <button type="button" class="btn-search" onclick="buscarnf()">🔍</button>
                            <input type="text" name="nf_cab_cod_part" id="val_nf_cab_cod_part" required >
                        </div>
                    </div>
                    <div class="field-group">
                        <label>Nome / Razão Social:</label>
                        <div class="search-group">
                            <input type="text" id="val_nf_cab_nome" name="nf_cab_nome" style="flex: 1;" required >
                            <button type="button" class="btn-search" onclick="buscarParticipante()">🔍</button>
                        </div>
                    </div>
                    <div class="field-group">
                        <label>Operação:</label>
                        <select name="nf_cab_c_v" id="val_nf_cab_c_v">
                            <option value="S">Saída</option>
                            <option value="E">Entrada</option>
                        </select>
                    </div>
                    <div class="field-group"><label>Status:</label><input type="text" name="nf_cab_status" id="val_nf_cab_status" value="P" readonly maxlength="1" style="text-align:center"></div>
                </div>
            </fieldset>

            <fieldset id="itens-fieldset">
                <legend>Itens e Produtos</legend>
                <div class="table-container">
                    <table id="tabelaItens">
                        <thead>
                            <tr>
                                <th width="110">Código</th>
                                <th>Descrição do Produto</th>
                                <th width="40">UN</th>
                                <th width="120">Nat. Operação</th>
                                <th width="70">Qtd</th>
                                <th width="90">Unitário</th>
                                <th width="70">Desc.</th>
                                <th width="90">Total</th>
                                <th width="70">Tributos</th>
                                <th width="30"></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <div class="tabs-grid-footer">
                    <div class="tabs-header">
                        <div class="tab-btn active" onclick="mudarAba(event, 'aba-valores')">Valores Gerais</div>
                        <div class="tab-btn" onclick="mudarAba(event, 'aba-impostos-v')">Valores Impostos</div>
                        <div class="tab-btn" onclick="mudarAba(event, 'aba-bases')">Bases de Cálculo</div>
                        <div class="tab-btn" onclick="mudarAba(event, 'aba-fiscal')">Dados Fiscais</div>
                        <div class="tab-btn" onclick="mudarAba(event, 'aba-pedido')">Referências</div>
                    </div>

                    <div id="aba-valores" class="tab-content active">
                        <div class="total-box">MERCADORIAS<span>R$ <span id="tot_merc">0,00</span></span></div>
                        <div class="total-box">FRETE<span>R$ <span id="tot_frete">0,00</span></span></div>
                        <div class="total-box">SEGURO<span>R$ <span id="tot_seguro">0,00</span></span></div>
                        <div class="total-box">OUTRAS DESP.<span>R$ <span id="tot_outros">0,00</span></span></div>
                        <div class="total-box">DESCONTO TOTAL<span>R$ <span id="tot_desc">0,00</span></span></div>
                        <div class="total-box">IPI TOTAL<span>R$ <span id="tot_ipi">0,00</span></span></div>
                    </div>

                    <div id="aba-impostos-v" class="tab-content">
                        <div class="total-box">VLR ICMS<span>R$ <span id="tot_v_icms">0,00</span></span></div>
                        <div class="total-box">VLR ICMS ST<span>R$ <span id="tot_v_st">0,00</span></span></div>
                        <div class="total-box">VLR PIS<span>R$ <span id="tot_v_pis">0,00</span></span></div>
                        <div class="total-box">VLR COFINS<span>R$ <span id="tot_v_cofins">0,00</span></span></div>
                        <div class="total-box">VLR PIS ST<span>R$ <span id="tot_v_pisst">0,00</span></span></div>
                        <div class="total-box">VLR COFINS ST<span>R$ <span id="tot_v_cofinsst">0,00</span></span></div>
                    </div>

                    <div id="aba-bases" class="tab-content">
                        <div class="total-box">BASE ICMS<span>R$ <span id="tot_b_icms">0,00</span></span></div>
                        <div class="total-box">BASE ICMS ST<span>R$ <span id="tot_b_st">0,00</span></span></div>
                        <div class="total-box">BASE PIS<span>R$ <span id="tot_b_pis">0,00</span></span></div>
                        <div class="total-box">BASE COFINS<span>R$ <span id="tot_b_cofins">0,00</span></span></div>
                        <div class="total-box">BASE IPI<span>R$ <span id="tot_b_ipi">0,00</span></span></div>
                        <div class="total-box">BASE ISSQN<span>R$ <span id="tot_b_issqn">0,00</span></span></div>
                    </div>

                    <div id="aba-fiscal" class="tab-content">
                        <div class="total-box">
                            <label>NÚMERO NF</label>
                            <input type="text" name="nf_num" id="val_nf_num" style="width:100%" placeholder="000.000.000">
                        </div>
                        <div class="total-box">
                            <label>SÉRIE</label>
                            <input type="text" name="nf_serie" id="val_nf_serie" style="width:100%" placeholder="1">
                        </div>
                        <div class="total-box">
                            <label>DATA EMISSÃO</label>
                            <input type="date" name="nf_dt_emi" id="val_nf_dt_emi" style="width:100%">
                        </div>
                        <div class="total-box">
                            <label>DATA ENT./SAÍDA</label>
                            <input type="date" name="nf_dt_ent_sai" id="val_nf_dt_ent_sai" style="width:100%">
                        </div>
                    </div>

                    <div id="aba-pedido" class="tab-content">
                        <div class="total-box">
                            <label>Nº PEDIDO</label>
                            <input type="text" name="nf_pedido" id="val_nf_pedido" style="width:100%" placeholder="Pedido Interno">
                        </div>
                        <div class="total-box">
                            <label>CHAVE DE ACESSO (NFe)</label>
                            <input type="text" name="nf_chave" id="val_nf_chave" style="width:100%" maxlength="44">
                        </div>
                    </div>
                </div>

                <div class="footer-bar">
                    <button type="button" class="btn-main" onclick="adicionarLinha()">+ INSERIR ITEM</button>
                    <button type="button" id="btnSalvar" class="btn-main" style="background: #008000; color: white;" onclick="salvarNF()">GRAVAR NF</button>
                </div>
            </fieldset>
        </form>

        <div class="status-bar">
            <div class="status-panel"><span>Pronto | Fiscal Ativo</span></div>
            <div class="status-panel">
                <span style="color:#000080">TOTAL NF: R$ </span><span id="grand_total" style="font-size: 14px; color: #b00000; font-weight: bold;">0,00</span>
                <input type="hidden" name="nf_cab_tot_nf" id="val_nf_cab_tot_nf" value="0.00">
            </div>
        </div>
    </div>
</div>

<div id="modalImpostos">
    <div class="modal-content">
        <div class="title-bar">
            <span>Detalhamento de Impostos do Item</span>
            <button type="button" onclick="fecharModal()" style="background:#c0c0c0; border:1px solid #000; cursor:pointer">X</button>
        </div>
        <div style="padding: 10px;">
            <div class="tax-grid">
                <div class="tax-section">
                    <h4>BASES</h4>
                    <label>B. ICMS</label><input type="number" step="0.01" id="m_base_icms" style="width:100%">
                    <label>B. ICMS ST</label><input type="number" step="0.01" id="m_base_st" style="width:100%">
                    <label>B. PIS</label><input type="number" step="0.01" id="m_base_pis" style="width:100%">
                    <label>B. COFINS</label><input type="number" step="0.01" id="m_base_cofins" style="width:100%">
                </div>
                <div class="tax-section">
                    <h4>ALÍQUOTAS (%)</h4>
                    <label>% ICMS</label><input type="number" step="0.01" id="m_aliq_icms" style="width:100%">
                    <label>% ICMS ST</label><input type="number" step="0.01" id="m_aliq_st" style="width:100%">
                    <label>% PIS</label><input type="number" step="0.01" id="m_aliq_pis" style="width:100%">
                    <label>% COFINS</label><input type="number" step="0.01" id="m_aliq_cofins" style="width:100%">
                </div>
                <div class="tax-section">
                    <h4>VALORES</h4>
                    <label>V. ICMS</label><input type="number" step="0.01" id="m_valor_icms" style="width:100%">
                    <label>V. ICMS ST</label><input type="number" step="0.01" id="m_valor_st" style="width:100%">
                    <label>V. PIS</label><input type="number" step="0.01" id="m_valor_pis" style="width:100%">
                    <label>V. COFINS</label><input type="number" step="0.01" id="m_valor_cofins" style="width:100%">
                </div>
            </div>
            <div class="tax-grid" style="grid-template-columns: 1fr 1fr;">
                 <div class="tax-section">
                    <h4>ST / OUTROS</h4>
                    <label>V. PIS ST</label><input type="number" step="0.01" id="m_valor_pisst" style="width:100%">
                    <label>V. COFINS ST</label><input type="number" step="0.01" id="m_valor_cofinsst" style="width:100%">
                    <label>Frete</label><input type="number" step="0.01" id="m_frete" style="width:100%">
                    <label>Desconto Item</label><input type="number" step="0.01" id="m_desconto" style="width:100%">
                </div>
                <div class="tax-section">
                    <h4>IPI / ISSQN / ETC</h4>
                    <label>V. IPI</label><input type="number" step="0.01" id="m_valor_ipi" style="width:100%">
                    <label>Seguro</label><input type="number" step="0.01" id="m_seguro" style="width:100%">
                    <label>Outros</label><input type="number" step="0.01" id="m_outros" style="width:100%">
                    <label>B. IPI</label><input type="number" step="0.01" id="m_base_ipi" style="width:100%">
                </div>
            </div>
            <div style="text-align:right; padding: 10px;">
                <button type="button" class="btn-main" onclick="confirmarImpostos()">OK / SALVAR</button>
            </div>
        </div>
    </div>
</div>

<script>
let rowCount = 0;
let currentRowId = null;

window.onload = () => { if(rowCount === 0) adicionarLinha(); };

// --- FUNÇÃO DE CARREGAMENTO DO BANCO ---
function carregarDadosDoBanco(dados) {
    // 1. Preenche Cabeçalho
    document.getElementById('val_codigo').value = dados.cabecalho.codigo;
    document.getElementById('val_nf_cab_cod_part').value = dados.cabecalho.nf_cab_cod_part;
    document.getElementById('val_nf_cab_nome').value = dados.cabecalho.nf_cab_nome;
    document.getElementById('val_nf_cab_c_v').value = dados.cabecalho.nf_cab_c_v;
    document.getElementById('val_nf_cab_status').value = dados.cabecalho.nf_cab_status;

    // 2. Preenche Novas Abas (se os dados existirem no JSON)
    if(document.getElementById('val_nf_num')) document.getElementById('val_nf_num').value = dados.cabecalho.nf_num || '';
    if(document.getElementById('val_nf_serie')) document.getElementById('val_nf_serie').value = dados.cabecalho.nf_serie || '';
    if(document.getElementById('val_nf_dt_emi')) document.getElementById('val_nf_dt_emi').value = dados.cabecalho.nf_cab_dt_emi || '';
    if(document.getElementById('val_nf_dt_ent_sai')) document.getElementById('val_nf_dt_ent_sai').value = dados.cabecalho.nf_cab_dt_ent_sai || '';
    if(document.getElementById('val_nf_pedido')) document.getElementById('val_nf_pedido').value = dados.cabecalho.nf_cab_pedido || '';
    if(document.getElementById('val_nf_chave')) document.getElementById('val_nf_chave').value = dados.cabecalho.nf_cab_chave || '';

    // 3. Limpa Tabela de Itens
    document.querySelector("#tabelaItens tbody").innerHTML = "";
    rowCount = 0;

    // 4. Adiciona Itens
    dados.itens.forEach(item => {
        adicionarLinha(item);
    });

    // 5. Recalcula Totais
    atualizarTotalGeral();
}

function adicionarLinha(item = null) {
    rowCount++;
    const tbody = document.querySelector("#tabelaItens tbody");
    const row = tbody.insertRow();
    const idRow = 'prod_' + rowCount;
    
    const cod    = item ? item.nf_itens_cod_item : '';
    const descr  = item ? item.nf_itens_descr_item : '';
    const unid   = item ? item.nf_itens_unid : 'UN';
    const nat    = item ? item.nfe_itens_nat_oper : 'VENDA';
    const qtd    = item ? item.item_qtd : '1.000';
    const vl     = item ? item.item_vl : '0.00';
    const dsc    = item ? item.item_desc : '0.00';
    const tot    = item ? item.item_tot : '0.00';

    row.innerHTML = `
        <td>
            <div class="search-group">
                <input type="text" name="item_cod[]" id="value_${idRow}" style="flex:1" value="${cod}" required>
                <button type="button" class="btn-search" onclick="buscarProduto('${idRow}')">🔍</button>
            </div>
        </td>
        <td><input type="text" name="item_descr[]" id="display_${idRow}" style="width:100%" readonly value="${descr}"></td>
        <td><input type="text" name="item_unid[]" id="unid_${idRow}" style="width:100%; text-align:center;" readonly value="${unid}"></td>
        <td><input type="text" name="nfe_itens_nat_oper[]" id="nat_${idRow}" style="width:100%" value="${nat}" required></td>
        <td><input type="number" name="item_qtd[]" style="width:100%" step="0.001" oninput="calcular(this)" value="${qtd}" required></td>
        <td><input type="number" name="item_vl[]" id="vl_${idRow}" style="width:100%" step="0.01" oninput="calcular(this)" value="${vl}" required></td>
        <td><input type="number" name="item_desc[]" style="width:100%" step="0.01" oninput="calcular(this)" value="${dsc}" required></td>
        <td><input type="text" name="item_tot[]" class="item-total" style="width:100%" readonly value="${tot}"></td>
        <td align="center">
            <button type="button" class="btn-tax" onclick="abrirModalImpostos('${idRow}')">Impostos</button>
            <div id="tax_data_${idRow}">
                <input type="hidden" name="tax_base_icms[]" value="0.00"> <input type="hidden" name="tax_aliq_icms[]" value="0.00"> <input type="hidden" name="tax_valor_icms[]" value="0.00">
                <input type="hidden" name="tax_base_st[]" value="0.00"> <input type="hidden" name="tax_aliq_st[]" value="0.00"> <input type="hidden" name="tax_valor_st[]" value="0.00">
                <input type="hidden" name="tax_base_pis[]" value="0.00"> <input type="hidden" name="tax_aliq_pis[]" value="0.00"> <input type="hidden" name="tax_valor_pis[]" value="0.00">
                <input type="hidden" name="tax_base_cofins[]" value="0.00"> <input type="hidden" name="tax_aliq_cofins[]" value="0.00"> <input type="hidden" name="tax_valor_cofins[]" value="0.00">
                <input type="hidden" name="tax_base_pisst[]" value="0.00"> <input type="hidden" name="tax_aliq_pisst[]" value="0.00"> <input type="hidden" name="tax_valor_pisst[]" value="0.00">
                <input type="hidden" name="tax_base_cofinsst[]" value="0.00"> <input type="hidden" name="tax_aliq_cofinsst[]" value="0.00"> <input type="hidden" name="tax_valor_cofinsst[]" value="0.00">
                <input type="hidden" name="tax_frete[]" value="0.00"> <input type="hidden" name="tax_seguro[]" value="0.00"> <input type="hidden" name="tax_outros[]" value="0.00">
                <input type="hidden" name="tax_base_ipi[]" value="0.00"> <input type="hidden" name="tax_valor_ipi[]" value="0.00">
                <input type="hidden" name="tax_base_issqn[]" value="0.00"> <input type="hidden" name="tax_aliq_issqn[]" value="0.00">
            </div>
        </td>
        <td><button type="button" style="color:red; background:none; border:none; font-weight:bold; cursor:pointer;" onclick="removerLinha(this)">X</button></td>
    `;
}

function calcular(el) {
    const row = el.closest('tr');
    const qtd = parseFloat(row.querySelector('[name="item_qtd[]"]').value) || 0;
    const vlUnit = parseFloat(row.querySelector('[name="item_vl[]"]').value) || 0;
    const desc = parseFloat(row.querySelector('[name="item_desc[]"]').value) || 0;
    const total = ((qtd * vlUnit) - desc).toFixed(2);
    row.querySelector('.item-total').value = total;
    atualizarTotalGeral();
}

function atualizarTotalGeral() {
    let s_merc = 0, s_desc = 0, s_ipi = 0, s_frete = 0, s_seg = 0, s_out = 0;
    let s_vicms = 0, s_vst = 0, s_vpis = 0, s_vcof = 0, s_vpisst = 0, s_vcofst = 0;
    let s_bicms = 0, s_bst = 0, s_bpis = 0, s_bcof = 0, s_bipi = 0, s_bissqn = 0;

    document.querySelectorAll("#tabelaItens tbody tr").forEach(row => {
        const q = parseFloat(row.querySelector('[name="item_qtd[]"]').value) || 0;
        const v = parseFloat(row.querySelector('[name="item_vl[]"]').value) || 0;
        s_merc += (q * v);
        s_desc += parseFloat(row.querySelector('[name="item_desc[]"]').value) || 0;

        const h = row.querySelector('div[id^="tax_data_"]').querySelectorAll('input');
        s_bicms += parseFloat(h[0].value) || 0;  s_vicms += parseFloat(h[2].value) || 0;
        s_bst   += parseFloat(h[3].value) || 0;  s_vst   += parseFloat(h[5].value) || 0;
        s_bpis  += parseFloat(h[6].value) || 0;  s_vpis  += parseFloat(h[8].value) || 0;
        s_bcof  += parseFloat(h[9].value) || 0;  s_vcof  += parseFloat(h[11].value) || 0;
        s_vpisst += parseFloat(h[14].value) || 0; s_vcofst += parseFloat(h[17].value) || 0;
        s_frete += parseFloat(h[18].value) || 0; s_seg   += parseFloat(h[19].value) || 0;
        s_out   += parseFloat(h[20].value) || 0; s_bipi  += parseFloat(h[21].value) || 0;
        s_ipi   += parseFloat(h[22].value) || 0; s_bissqn += parseFloat(h[23].value) || 0;
    });

    document.getElementById('tot_merc').innerText = s_merc.toLocaleString('pt-BR',{minimumFractionDigits:2});
    document.getElementById('tot_frete').innerText = s_frete.toLocaleString('pt-BR',{minimumFractionDigits:2});
    document.getElementById('tot_desc').innerText = s_desc.toLocaleString('pt-BR',{minimumFractionDigits:2});
    document.getElementById('tot_v_icms').innerText = s_vicms.toLocaleString('pt-BR',{minimumFractionDigits:2});
    document.getElementById('tot_v_st').innerText = s_vst.toLocaleString('pt-BR',{minimumFractionDigits:2});
    
    const grandTotal = (s_merc - s_desc) + s_vst + s_ipi + s_frete + s_seg + s_out;
    document.getElementById('grand_total').innerText = grandTotal.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
    document.getElementById('val_nf_cab_tot_nf').value = grandTotal.toFixed(2);
}

function mudarAba(evt, abaId) {
    let i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) { tabcontent[i].classList.remove("active"); }
    tablinks = document.getElementsByClassName("tab-btn");
    for (i = 0; i < tablinks.length; i++) { tablinks[i].classList.remove("active"); }
    document.getElementById(abaId).classList.add("active");
    evt.currentTarget.classList.add("active");
}

function abrirModalImpostos(rowId) {
    currentRowId = rowId;
    const container = document.getElementById('tax_data_' + rowId);
    const inputs = container.querySelectorAll('input');
    
    document.getElementById('m_base_icms').value = inputs[0].value;
    document.getElementById('m_aliq_icms').value = inputs[1].value;
    document.getElementById('m_valor_icms').value = inputs[2].value;
    document.getElementById('modalImpostos').style.display = 'block';
}

function fecharModal() { document.getElementById('modalImpostos').style.display = 'none'; }

function confirmarImpostos() {
    const container = document.getElementById('tax_data_' + currentRowId);
    const inputs = container.querySelectorAll('input');
    inputs[0].value = document.getElementById('m_base_icms').value;
    inputs[1].value = document.getElementById('m_aliq_icms').value;
    inputs[2].value = document.getElementById('m_valor_icms').value;
    calcular(container.closest('tr').querySelector('[name="item_qtd[]"]'));
    fecharModal();
}

function removerLinha(btn) {
    if(document.querySelectorAll("#tabelaItens tbody tr").length > 1) {
        btn.closest('tr').remove();
        atualizarTotalGeral();
    }
}

function buscarnf() { window.open('busca_nf.php', 'Busca', 'width=850,height=600,scrollbars=yes'); }
function buscarParticipante() { window.open('busca_participante.php', 'Busca', 'width=750,height=550'); }
function buscarProduto(id) { window.open('busca_produto.php?target=' + id, 'BuscaProd', 'width=600,height=500'); }

function salvarNF() {
    const btn = document.getElementById('btnSalvar');
    btn.innerText = "Gravando...";
    const formData = new FormData(document.getElementById('orcForm'));
    fetch('processar_nf.php', { method: 'POST', body: formData })
    .then(r => r.text())
    .then(d => { alert("Registro Salvo com Sucesso!"); location.reload(); })
    .catch(e => alert("Erro ao salvar."));
}
</script>
</body>
</html>